package com.hdl.school.utils;

import static java.lang.Integer.parseInt;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hdl.school.application.MyApplication;
import com.hdl.school.bean.SerialHexCode;
import com.hdl.school.bean.SerialMessage;
import com.hdl.school.bean.TemporarySerialHexMessage;
import com.hdl.school.common.ControllerVersion;
import com.hdl.school.entity.HexCodeQueue;
import com.hdl.school.entity.SerialportInfo;
import com.hdl.school.schoolcontroller.BuildConfig;
import com.hdl.school.schoolcontroller.MainActivity;
import com.hdl.school.schoolcontroller.R;
import com.leectrl.bean.ZigbeeDevice;
import com.leectrl.utils.Bus;
import com.leectrl.utils.DbUtil;
import com.likong.iotsdk.DeviceType;
import com.likong.iotsdk.RoomInfo;

import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.f1reking.serialportlib.SerialPortHelper;
import me.f1reking.serialportlib.listener.IOpenSerialPortListener;
import me.f1reking.serialportlib.listener.ISerialPortDataListener;
import me.f1reking.serialportlib.listener.Status;


public class USBSerialManager {
    private Object i = new Object();
    private Object j = new Object();
    private static USBSerialManager usbSerialManager;
    private UsbManager um = null;
    private Semaphore A = new Semaphore(1);
    private int s = 0;
    private byte[] n = new byte[655360];
    private byte[] o = new byte[8092];
    private int p = 0;
    private int q = 0;
    private int w = 1000;
    private long serialCodeInterval = 100;
    private static byte dataBit = 8;           //数据位
    private static byte stopBit = 1;           //停止位
    private static byte parity = 0;            //校验
    private static byte flowControl = 0;       //流控
    private Context mContext;
    private static ControllerVersion controllerVersion = Constants.CONTROLLER_VERSION;

    private ConcurrentHashMap<String, USBMap> usbHashMap = new ConcurrentHashMap();
    private List<UsbDevice> permissionReqArr = Collections.synchronizedList(new ArrayList<UsbDevice>());
    private PendingIntent pendingIntent;
    private USBReceiver usbReceiver;
    private static Map<String, String> portRef = new HashMap<>();
    private static Map<String, String> nameRef = new HashMap<>();
    private static Map<String, String> dymicPortRef = new HashMap<>();
    private static ConcurrentHashMap<String, SerialPortHelper> ttyRef = new ConcurrentHashMap<>();
    private List<String> registedDevices = new ArrayList<>();
    private static ConcurrentHashMap<String, SerialportInfo> serialportConfigs = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, HexCodeQueue> codeQueueMap = new ConcurrentHashMap<String, HexCodeQueue>();
    private ConcurrentHashMap<String, SerialportInfo> serialQueueMap = new ConcurrentHashMap<>();
    private List<JSONObject> statusParser;
    private ConcurrentHashMap<String, String> serialKeyMap = new ConcurrentHashMap<>();


    public static final String ACTION_USB_PERMISSION = "com.leectrl.terminal.USB_PERMISSION";
    //中控端口
    private static final String MAIN_TTL_PORT = "ttyS7";
    private static final String MAIN_TTL = "ttl";
    private static final String PANEL_TTL_PORT = "ttyS5";
    private static final String CONTROLPANEL = "controlpanel";
    //hdmi矩阵端口
    private static final String HDMI_TTL_PORT = "ttyS4";
    //hdmi矩阵
    private static final String HDMIMATRIX = "hdmimatrix";
    private static boolean debugEnable = false;
    private JSONObject serialSuccessMap = new JSONObject();
    private static SharedPreferences sharedPreferences;
    private RoomInfo roomInfo;
    private boolean inClass = false;
    private String customOpenCode = null;
    private String customCloseCode = null;
    private Map<String, String> defaultActionCodeMap = new HashMap();
    //录播状态缓存 1录播电源状态(off关 on开） 2直播状态(off on正在直播） 3录制状态（off未录制 on正在录制 pause暂停录制）
    String[] recorderStatus = new String[]{"on", "off", "off"};
    private boolean airctrlStatusEnable = true;

    public boolean isAirctrlStatusEnable() {
        return airctrlStatusEnable;
    }

    public void setAirctrlStatusEnable(boolean airctrlStatusEnable) {
        this.airctrlStatusEnable = airctrlStatusEnable;
    }

    public boolean isInClass() {

        return inClass;
    }

    public void setInClass(boolean inClass) {
        this.inClass = inClass;
    }

    Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    synchronized (permissionReqArr) {
                        if (permissionReqArr.size() > 0) {
                            sendLogMessage(new SerialMessage(getPortByPath(permissionReqArr.get(0).getDeviceName()), "请求权限", "SYS"));
                            synchronized (um) {
                                um.requestPermission(permissionReqArr.get(0), pendingIntent);
                            }
                            permissionReqArr.remove(0);
                        }
                    }

                    break;
                case 3:
                    Intent intent = new Intent(Constants.ACTION_SETIAL_MSG);
                    SerialMessage serialMessage = (SerialMessage) msg.obj;
                    intent.putExtra("serial_msg", JSON.toJSONString(serialMessage));
                    if(mContext != null){
                        mContext.sendBroadcast(intent);
                    }
                    break;
                case 10:
                    if (controllerVersion.equals(ControllerVersion.OLD)) {
                        String[] checkPort = new String[]{MAIN_TTL_PORT, HDMI_TTL_PORT, "USB1", "USB2", "USB3", "USB4", "USB5"};
                        for (int j = 0; j < checkPort.length; j++) {
                            if (!(serialSuccessMap.containsKey(checkPort[j]))) {
                                TCWManager.getInstance(MyApplication.myApplication).reboot();
                                break;
                            }
                        }
                    }

                    break;
                case 11:
                    break;
                case 76:
                    Bus.getInstance().emit("screen_share", msg.obj);
                    break;
                case 99:
                    break;
                case 109:
                //     doCustomAction("ceee0e0000eeec",null,CONTROLPANEL);
                    break;
                case 1001:
                    // sendCtrlSerialCode("CEECFFCFFC0D08FE000250010A5DFFFCCF");
                    break;
                case 9998:
                    if(roomInfo==null){
                       return ;
                    }
                    int roomId=roomInfo.getRoomId();
                    String serverConfig=sharedPreferences.getString("serverConfig",null);
                    if(serverConfig==null){
                        return ;
                    }
                    RequestParams requestParams = new RequestParams();
                    requestParams.setUri("http://" + serverConfig + "/deviceapi/iot/airctrl/broad/settings/load");
                    requestParams.setAsJsonContent(true);
                    JSONObject body = new JSONObject();
                    body.put("room", roomId);
                    requestParams.setBodyContent(JSON.toJSONString(body));
                    x.http().post(requestParams, new org.xutils.common.Callback.CommonCallback<String>() {

                        @Override
                        public void onSuccess(String result) {
                            try{
                                JSONObject resp=JSON.parseObject(result);
                                if(resp.getIntValue("code")==0){
                                    String respHex="CEEE0E";
                                    String contentHex="01";
                                    JSONObject data=resp.getJSONObject("data");
                                    int lowTemp=data.getIntValue("lowTemp");
                                    int highTemp=data.getIntValue("highTemp");
                                    if(lowTemp<0){
                                        contentHex+="00";
                                    }else{
                                        contentHex+="01";
                                    }
                                    String lowTempHex=Integer.toHexString(Math.abs(lowTemp)).toUpperCase();
                                    if(lowTempHex.length()<2){
                                        lowTempHex="0"+lowTempHex;
                                    }
                                    contentHex+=lowTempHex;
                                    if(highTemp<0){
                                        contentHex+="00";
                                    }else{
                                        contentHex+="01";
                                    }
                                    String highTempHex=Integer.toHexString(Math.abs(highTemp)).toUpperCase();
                                    if(highTempHex.length()<2){
                                        highTempHex="0"+highTempHex;
                                    }
                                    contentHex+=highTempHex;
                                    JSONArray freeAddress=data.getJSONArray("freeAddress");
                                    String addrLenHex=Integer.toHexString(freeAddress.size()).toUpperCase();
                                    if(addrLenHex.length()<2){
                                        addrLenHex="0"+ addrLenHex;
                                    }
                                    contentHex+=addrLenHex;
                                    for(int k=0;k<freeAddress.size();k++){
                                        contentHex+=freeAddress.getString(k);
                                    }
                                    JSONArray freeDur=data.getJSONArray("freeDur");
                                    String durLenHex=Integer.toHexString(freeDur.size()).toUpperCase();
                                    if(durLenHex.length()<2){
                                        durLenHex="0"+ durLenHex;
                                    }
                                    contentHex+=durLenHex;
                                    for(int k=0;k<freeDur.size();k++){
                                        JSONArray dur=freeDur.getJSONArray(k);
                                        String t1=HexUtil.timeToHex(dur.getString(0));
                                        String t2=HexUtil.timeToHex(dur.getString(1));
                                        if(t1!=null&&t2!=null){
                                            contentHex+=t1;
                                            contentHex+=t2;
                                        }

                                    }
                                    int length=contentHex.length()/2;
                                    if(length<16){
                                        respHex+=("0"+Integer.toHexString(length).toUpperCase());
                                    }else{
                                        respHex+=Integer.toHexString(length).toUpperCase();
                                    }
                                    respHex+="00";
                                    respHex+=contentHex;
                                    respHex+="EEEC";
                                    sendCtrlSerialCode(CONTROLPANEL,respHex);
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {

                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                    break;
                case 9999:
                    CardReaderManager.getInstance().checkCard((String) msg.obj);
                    break;
            }
        }
    };





    private USBSerialManager() {
        String roomInfoStr = sharedPreferences.getString("room_info", null);
        if (roomInfoStr != null) {
            roomInfo = JSON.parseObject(roomInfoStr, RoomInfo.class);
        }
        String customSysCode = sharedPreferences.getString("customSysCode", null);
        if (customSysCode != null) {
            JSONObject customCodeObj = JSON.parseObject(customSysCode);
            customOpenCode = customCodeObj.getString("openCode").replaceAll(" ", "").toLowerCase();
            customCloseCode = customCodeObj.getString("closeCode").replaceAll(" ", "").toLowerCase();
        }
        InputStream in = MyApplication.myApplication.getResources().openRawResource(R.raw.actions);
        int length = 0;
        try {
            length = in.available();
            byte[] buffer = new byte[length];
            in.read(buffer);
            String defaultActionStr = new String(buffer);
            JSONArray defaultActionArr = JSON.parseArray(defaultActionStr);
            for (int j = 0; j < defaultActionArr.size(); j++) {
                JSONObject obj = defaultActionArr.getJSONObject(j);
                if (!("custom".equals(obj.getString("key")))) {
                    defaultActionCodeMap.put(obj.getString("key"), obj.getString("code"));
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //handler.sendEmptyMessageDelayed(1001,6000);
        // handler.sendEmptyMessageDelayed(109, 8000);
    }

    public static USBSerialManager getInstence() {
        if (usbSerialManager == null) {
            File file = new File("/dev/bus/usb/001/008");
            if (file.exists()) {
                controllerVersion = ControllerVersion.NEW;
                Constants.CONTROLLER_VERSION = ControllerVersion.NEW;
            } else {
                File interfaceBroadFile = new File("/dev/bus/usb/002/006");
                File interfaceBroadFile2 = new File("/dev/bus/usb/002/005");
                if (interfaceBroadFile.exists() && interfaceBroadFile2.exists()) {
                    controllerVersion = ControllerVersion.OLD;
                    Constants.CONTROLLER_VERSION = ControllerVersion.OLD;
                } else {
                    controllerVersion = ControllerVersion.IOT_GATEWAY;
                    Constants.CONTROLLER_VERSION = ControllerVersion.IOT_GATEWAY;
                }

            }
            /*******旧版接口板***********/
            if (controllerVersion.equals(ControllerVersion.OLD)) {
                //RS485
                portRef.put("USB1", "/dev/bus/usb/002/003");
                nameRef.put("USB1", "RS485-1");
                portRef.put("USB2", "/dev/bus/usb/002/004");
                nameRef.put("USB2", "RS485-2");
                portRef.put("USB3", "/dev/bus/usb/002/005");
                nameRef.put("USB3", "RS485-3");
                //Rs232
                portRef.put("USB4", "/dev/bus/usb/002/006");
                nameRef.put("USB4", "RS232");
                //面板
                //fengyouchun
                /*if (BuildConfig.DEBUG) {
                    portRef.put("USB5", "/dev/bus/usb/004/003");
                } else {
                    portRef.put("USB5", "/dev/bus/usb/006/002");
                }*/
                //面板
                //liuyong
                if (BuildConfig.DEBUG) {
                    portRef.put("USB5", "/dev/bus/usb/003/002");
                } else {
                    portRef.put("USB5", "/dev/bus/usb/006/002");
                }
                nameRef.put("USB5", "面板");
                //刷卡器
                portRef.put("USB6", "/dev/bus/usb/003/*");
                nameRef.put("USB6", "刷卡器");
            } else if (controllerVersion.equals(ControllerVersion.NEW)) {
                //RS485-1
                portRef.put("USB1", "/dev/bus/usb/001/003");
                nameRef.put("USB1", "RS485-1");
                //RS485-2
                portRef.put("USB2", "/dev/bus/usb/001/004");
                nameRef.put("USB2", "RS485-2");
                //RS485-3
                portRef.put("USB3", "/dev/bus/usb/001/005");
                nameRef.put("USB3", "RS485-3");
                //RS485-4
                portRef.put("ttyS5", "/dev/ttyS5");
                nameRef.put("ttyS5", "RS485-4");
                //RS232-4
                portRef.put("USB5", "/dev/bus/usb/001/008");
                nameRef.put("USB5", "RS232-4");
                //RS232-3
                portRef.put("USB6", "/dev/bus/usb/001/007");
                nameRef.put("USB6", "RS232-3");
                //RS232-2
                portRef.put("USB7", "/dev/ttyS4");
                nameRef.put("USB7", "RS232-2");
                //RS232-1
                portRef.put("USB8", "/dev/bus/usb/001/009");
                nameRef.put("USB8", "RS232-1");
                //红外
                portRef.put("USB9", "/dev/bus/usb/001/006");
                nameRef.put("USB9", "IR");
                //刷卡器
                portRef.put("USB10", "/dev/bus/usb/006/002");
                nameRef.put("USB10", "USB-1-2");
            } else if (controllerVersion.equals(ControllerVersion.IOT_GATEWAY)) {
                //RS485-1
                portRef.put("ttyS0", "/dev/ttyS0");
                nameRef.put("ttyS0", "ttyS0");

                //RS485-2
                portRef.put("ttyS5", "/dev/ttyS5");
                nameRef.put("ttyS5", "ttyS5");

                //RS232-1
                portRef.put("ttyS2", "/dev/ttyS2");
                nameRef.put("ttyS2", "ttyS2");

                //RS232-1
                portRef.put("ttyS4", "/dev/ttyS4");
                nameRef.put("ttyS4", "ttyS4");
            }
            /*******新版接口板***********/
            sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
            String serialportConfig = sharedPreferences.getString("serialport", null);
            if (serialportConfig != null) {
                JSONObject object = JSON.parseObject(serialportConfig);
                for (int i = 0; i <= 10; i++) {
                    if (object.containsKey("serialUSB" + i)) {
                        serialportConfigs.put("USB" + i, new SerialportInfo(object.getJSONObject("serialUSB" + i)));
                    }
                    if (object.containsKey("ttyS" + i)) {
                        serialportConfigs.put("ttyS" + i, new SerialportInfo(object.getJSONObject("ttyS" + i)));
                    }
                }
            } else {
                if (controllerVersion.equals(ControllerVersion.NEW)) {
                    serialportConfig = "{\"serialUSB10\":{\"baudRate\":\"9600\",\"portName\":\"cardreader\"},\"serialUSB6\":{\"baudRate\":\"9600\",\"portName\":\"computer\"},\"serialUSB2\":{\"baudRate\":\"9600\",\"portName\":\"airpower\"},\"ttyS4\":{\"baudRate\":\"115200\",\"portName\":\"recordinghost\"},\"serialUSB9\":{\"baudRate\":\"9600\",\"portName\":\"\"},\"serialUSB8\":{\"baudRate\":\"9600\",\"portName\":\"pctablet\"},\"serialUSB1\":{\"baudRate\":\"19200\",\"portName\":\"airctrl\"},\"ttyS0\":{\"baudRate\":\"9600\",\"portName\":\"\"},\"ttyS5\":{\"baudRate\":\"9600\",\"portName\":\"controlpanel\"},\"serialUSB5\":{\"baudRate\":\"9600\",\"portName\":\"other1\"},\"ttyS2\":{\"baudRate\":\"9600\",\"portName\":\"hdmimatrix\"},\"serialUSB3\":{\"baudRate\":\"9600\",\"portName\":\"envsensor\"}}";
                } else if (controllerVersion.equals(ControllerVersion.OLD)) {
                    //fengyouchun
                    //serialportConfig = "{\"serialUSB6\":{\"baudRate\":\"9600\",\"portName\":\"cardreader\"},\"serialUSB2\":{\"baudRate\":\"9600\",\"portName\":\"airpower\"},\"serialUSB1\":{\"baudRate\":\"19200\",\"portName\":\"airctrl\"},\"serialUSB7\":{\"baudRate\":\"9600\",\"portName\":\"\"},\"serialUSB5\":{\"baudRate\":\"9600\",\"portName\":\"controlpanel\"},\"serialUSB4\":{\"baudRate\":\"115200\",\"portName\":\"recordinghost\"},\"serialUSB3\":{\"baudRate\":\"9600\",\"portName\":\"envsensor\"}}";
                    //liuyong
                    serialportConfig = "{\"serialUSB6\":{\"baudRate\":\"9600\",\"portName\":\"cardreader\"},\"serialUSB2\":{\"baudRate\":\"9600\",\"portName\":\"airpower\"},\"serialUSB1\":{\"baudRate\":\"19200\",\"portName\":\"airctrl\"},\"serialUSB7\":{\"baudRate\":\"9600\",\"portName\":\"\"},\"serialUSB5\":{\"baudRate\":\"9600\",\"portName\":\"controlpanel\"},\"serialUSB4\":{\"baudRate\":\"115200\",\"portName\":\"recordinghost\"},\"serialUSB3\":{\"baudRate\":\"9600\",\"portName\":\"envsensor\"},\"ttyS4\":{\"baudRate\":\"9600\",\"portName\":\"hdmimatrix\"}}";

                } else if (controllerVersion.equals(ControllerVersion.IOT_GATEWAY)) {
                    serialportConfig = "{\"ttyS0\":{\"baudRate\":\"19200\",\"portName\":\"airctrl\"},\"ttyS2\":{\"baudRate\":\"9600\",\"portName\":\"\"},\"ttyS4\":{\"baudRate\":\"9600\",\"portName\":\"\"},\"ttyS5\":{\"baudRate\":\"9600\",\"portName\":\"\"}}";
                }
                sharedPreferences.edit().putString("serialport", serialportConfig).commit();
                JSONObject object = JSON.parseObject(serialportConfig);
                for (int i = 0; i <= 10; i++) {
                    if (object.containsKey("serialUSB" + i)) {
                        serialportConfigs.put("USB" + i, new SerialportInfo(object.getJSONObject("serialUSB" + i)));
                    }
                    if (object.containsKey("ttyS" + i)) {
                        serialportConfigs.put("ttyS" + i, new SerialportInfo(object.getJSONObject("ttyS" + i)));
                    }
                }
            }
            usbSerialManager = new USBSerialManager();

        }

        return usbSerialManager;
    }

    public void setDebugEnable(boolean enable) {
        debugEnable = enable;
    }


    public void setStatusParser(List<JSONObject> statusParser) {
        this.statusParser = statusParser;
    }

    public void setSerialKey(String port, String key) {
        serialKeyMap.put(port, key);
    }


    public void attachContext(Context context) {
        //读取设备类型的配置
        this.mContext = context;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(context, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
        }
        //pendingIntent = PendingIntent.getActivity(context, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE);
        usbReceiver = new USBReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_USB_PERMISSION);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        context.registerReceiver(usbReceiver, intentFilter);
        um = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> devices = um.getDeviceList();
        Iterator it = devices.values().iterator();
        while (it.hasNext()) {
            UsbDevice usbDevice = (UsbDevice) it.next();
            if (String.format("%04x:%04x", usbDevice.getVendorId(), usbDevice.getProductId()).equals("1a86:7523")) {
                if (um.hasPermission(usbDevice)) {
                    sendLogMessage(new SerialMessage(usbDevice.getDeviceName(), "初始化...", "SYS"));
                    boolean initRes = attachUSB(usbDevice);
                    final String port = getPortByPath(usbDevice.getDeviceName());
                    sendLogMessage(new SerialMessage(getPortName(port), initRes ? "初始化成功" : "初始化失败", "SYS"));
                    if (initRes) {
                        serialSuccessMap.put(port, true);
                        SerialportInfo serialportInfo = serialportConfigs.get(port);
                        if (serialportInfo != null && (!TextUtils.isEmpty(serialportInfo.getPortName()))) {
                            serialQueueMap.put(port, serialportInfo);
                            if ("cardreader".equals(serialportInfo.getPortName())) {
                                sendSerialMessageFromPort(port, true, "FE010300ED0594D7FFFF");
                            }
                        }


                    }

                } else {
                    permissionReqArr.add(usbDevice);
                }
            }
        }
        if (permissionReqArr.size() > 0) {
            for (int i = 0; i < permissionReqArr.size(); i++) {
                handler.sendEmptyMessageDelayed(1, 1000 * i);
            }
        }
        SerialPortHelper serialPortHelper = new SerialPortHelper();
        String[] paths = serialPortHelper.getAllDeicesPath();
        for (final String path : paths) {
            if (path.startsWith("/dev/ttyS")) {
                String baudRate = "9600";
                String ttyPort = path.substring(path.lastIndexOf("/") + 1);
                if (ttyPort != null) {
                    SerialportInfo serialportInfo = serialportConfigs.get(ttyPort);
                    if ((serialportInfo != null && (!TextUtils.isEmpty(serialportInfo.getPortName())))) {
                        String br = serialportInfo.getBaudRate();
                        if (br != null && br.length() > 0) {
                            baudRate = br;
                        }
                    } else {
                        if (!(MAIN_TTL_PORT.equals(ttyPort))) {
                            continue;
                        }
                    }
                    SerialPortHelper.Builder serial = new SerialPortHelper.Builder(path, parseInt(baudRate));
                    SerialPortHelper serialPortHelper1 = serial.build();
                    serialPortHelper1.setISerialPortDataListener(new ISerialPortDataListener() {
                        @Override
                        public void onDataReceived(String hexString) {
                            String ttyPath = path.substring(path.lastIndexOf("/") + 1);
                            sendLogMessage(new SerialMessage(ttyPath, hexString.toUpperCase(), "RX"));
                            onReceiveSerialCode(ttyPath, hexString.toLowerCase().replaceAll(" ", ""));
                        }

                        @Override
                        public void onDataSend(byte[] bytes) {
                            // String revMsg = byte2HexString(bytes, bytes.length);
                            // sendLogMessage(new SerialMessage(path.substring(path.lastIndexOf("/") + 1), revMsg.toUpperCase(), "TX"));
                        }
                    });
                    serialPortHelper1.setIOpenSerialPortListener(new IOpenSerialPortListener() {
                        @Override
                        public void onSuccess(File device) {
                            final String port = path.substring(path.lastIndexOf("/") + 1);
                            serialSuccessMap.put(port, true);
                            sendLogMessage(new SerialMessage(getPortName(port), "打开成功", "SYS"));
                            serialQueueMap.put(port, serialportInfo);
                        }

                        @Override
                        public void onFail(File device, Status status) {
                            sendLogMessage(new SerialMessage(path.substring(path.lastIndexOf("/") + 1), "打开失败", "SYS"));
                        }
                    });
                    serialPortHelper1.open();
                    ttyRef.put(path, serialPortHelper1);
                }
            }
        }
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Set<String> serialQueuePorts = codeQueueMap.keySet();
                synchronized (serialQueuePorts) {
                    for (String port : serialQueuePorts) {
                        //port为ttyS*或者USB*
                        HexCodeQueue hexCodeQueue = codeQueueMap.get(port);
                        if (hexCodeQueue == null) {
                            continue;
                        }
                        SerialHexCode serialHexCode = hexCodeQueue.getFirstOveredCode();
                        if (serialHexCode != null) {
                            String serialKey = serialHexCode.getKey();
                            if (serialKey != null) {
                                setSerialKey(port, serialKey);
                            }
                            String code = serialHexCode.getCode().replaceAll(" ", "").toLowerCase();
                            if ("TCP".equals(port)) {
                                sendLogMessage(new SerialMessage("TCP", code, "TX"));
                                Bus.getInstance().emit("tcp_serial", code);
                            } else {
                                sendSerialMessageFromPort(port, true, code);
                            }
                        }

                    }
                }


            }
        }, 0, 600);
    }

    private void onReceiveSerialCode(String portPath, String code) {
        if (portPath == null) {
            return;
        }

        Log.d("dzkStatus", "onReceiveSerialCode: "+portPath+"-----"+code);

        code = code.replaceAll(" ", "").toLowerCase();
        String mPortType = null;
        SerialportInfo serialportInfo = serialportConfigs.get(portPath);
        if (serialportInfo != null) {
            mPortType = serialportInfo.getPortName();
        } else {
            if (portPath.equals(MAIN_TTL_PORT)) {
                mPortType = MAIN_TTL;
            } else if (portPath.equals(HDMI_TTL_PORT) && (!ControllerVersion.IOT_GATEWAY.equals(controllerVersion))) {
                mPortType = HDMIMATRIX;
            } else if (portPath.equals(PANEL_TTL_PORT) && (!ControllerVersion.IOT_GATEWAY.equals(controllerVersion))) {
                mPortType = CONTROLPANEL;
            }
        }
        if (mPortType == null) {
            return;
        }
        String serialKey = null;
        if (serialKeyMap.containsKey(portPath)) {
            serialKey = serialKeyMap.get(portPath);
        }
        JSONObject outputObj = StatusParser.getInstance().parseStatus(mPortType, code, serialKey);
        if (outputObj != null) {
            JSONObject statusFeedbackObj = new JSONObject();
            statusFeedbackObj.put("action", "status_feedback");
            statusFeedbackObj.put("status", outputObj);
            //liuyong
            /*if(outputObj.containsKey("controller")  && outputObj.getString("controller").equals("on")){
                inClass = true;
            }else if(outputObj.containsKey("controller")  && outputObj.getString("controller").equals("off")){
                inClass = false;
            }*/
            Bus.getInstance().emit("publish_feedback_msg", statusFeedbackObj);
            Bus.getInstance().emit("status_feedback", outputObj);
            Bus.getInstance().emit("scene_event", "status_feedback", outputObj);
            if (outputObj.containsKey("recorder")) {
                recorderStatus[2] = outputObj.getString("recorder");
            }
            if (outputObj.containsKey("recorder_living")) {
                recorderStatus[1] = outputObj.getString("recorder_living");
            }
        }

        //中控相关配置缓存
        if (portPath.equals(MAIN_TTL_PORT)) {
            Pattern pattern2 = Pattern.compile("^fe00f0000100f1fffe0002[0-9a-f]*ff$");
            Matcher matcher2 = pattern2.matcher(code);
            if (matcher2.find()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("time", System.currentTimeMillis());
                jsonObject.put("code", code);
                sharedPreferences.edit().putString("setting_" + code.substring(22, 24), JSON.toJSONString(jsonObject)).commit();
            } else {
                if (code.startsWith("fe00025702")) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("time", System.currentTimeMillis());
                    jsonObject.put("code", code);
                    sharedPreferences.edit().putString("setting_" + code.substring(6, 8), JSON.toJSONString(jsonObject)).commit();
                }
            }
        } else if (mPortType.equals("airctrl")) {
            Pattern pattern3 = Pattern.compile("^fd[0-9a-f]{4}0041[0-9a-f]*efff$");
            Matcher matcher3 = pattern3.matcher(code);
            if (matcher3.find()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("time", System.currentTimeMillis());
                jsonObject.put("code", code);
                sharedPreferences.edit().putString("setting_fd_" + code.substring(6, 10), JSON.toJSONString(jsonObject)).commit();
            }
        }
        //liuyong 无实际作用
        Bus.getInstance().emit("receive_serial_code", portPath, mPortType, code);
        //liuyong 执行自定义指令
        doCustomAction(code, portPath, mPortType);
    }
    
    /**
     * 执行自定义指令
     *
     * @param code
     */
    public void doCustomAction(String code, String portPath, String portName) {
        if (CONTROLPANEL.equals(portName)) {
            long now = System.currentTimeMillis();
            if (code.equals(customOpenCode)) {
                Bus.getInstance().emit("exec_action", "in_class", null, null, 5);
            } else if (code.equals(customCloseCode)) {
                Bus.getInstance().emit("exec_action", "over_class", null, null, 5);
            } else if ((new RegExp("^fe010200cc00")).test(code)) {
                //fe010200cc000a010ba0f00400ee036f23ddddffff
                //  console.log(myUtil.time_now()+">serial ttl message:"+code)
                String targetCode = code.substring(16, 18);
                if (targetCode.equals("0b")) {
                    //Zigbee方式控制
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("action", "ctrlzigbee");
                    jsonObject.put("code", code.substring(14, code.length() - 8));
                    Bus.getInstance().emit("publish_zigbee_msg", jsonObject);
                } else if (targetCode.equals("0c")) {
                    //RS485方式本地控制
                    String mCode = code.substring(14, code.length() - 8);
                    String devTypeTag = mCode.substring(4, 6).toUpperCase();
                    String actionTag = mCode.substring(6, 8).toUpperCase();
                    String dataTag = mCode.substring(14, 16).toUpperCase();
//                    if (devTypeTag == "A3") {
//                        //控空调
//                        if (actionTag == "F0") {
//                            //开关
//                            if (dataTag == "26" || dataTag == "27") {
//                                Bus.getInstance().emit("exec_action", (dataTag == "26" ? "open_airctrl_switcher" : "close_airctrl_switcher"), {
//                                        location: [parseInt(mCode.slice(8, 10), 16)]
//                        },"airctrl")
//                            } else if (dataTag == "01" || dataTag == "02") {
//                                bus.emit('exec_action', (dataTag == "01" ? 'open_airctrl_power' : 'close_airctrl_power'), {
//                                        location: [parseInt(mCode.slice(8, 10), 16)]
//                        }, 'airctrl')
//                            }
//
//                        } else if (actionTag == "F1") {
//                            //调温
//                            bus.emit('exec_action', 'set_airctrl_temprature', {
//                                    location: [parseInt(mCode.slice(8, 10), 16)],
//                            temperature: [parseInt(dataTag, 16)]
//                    }, 'airctrl')
//                        } else if (actionTag == "F2") {
//                            //模式
//                            bus.emit('exec_action', 'set_airctrl_mode', {
//                                    location: [parseInt(mCode.slice(8, 10), 16)],
//                           mode: [parseInt(dataTag, 16) - 33]
//                    }, 'airctrl')
//                        } else if (actionTag == "F3") {
//                            //风速
//                            bus.emit('exec_action', 'set_airctrl_speed', {
//                                    location: [parseInt(mCode.slice(8, 10), 16)],
//                            speed: [parseInt(dataTag, 16) - 34]
//                    })
//                        }
//                    } else if (devTypeTag == "A2") {
//                        if (dataTag == "01" || dataTag == "02" || dataTag == "03") {
//                            String tag = null;
//                            switch (dataTag) {
//                                case "01":
//                                    tag = "window_open";
//                                    break;
//                                case "02":
//                                    tag = "window_close";
//                                    break;
//                                case "03":
//                                    tag = "stop_rotate";
//                                    break;
//                            }
//                            bus.emit('exec_action', tag, {
//                                    location: [parseInt(mCode.slice(8, 10), 16)]
//                    })
//                        }
//                    }
                }
            } else if ((new RegExp("^cffc[0-9a-f]{8,}fccf$")).test(code)) {
                //USB串口控制
                if (code.equals("cffc0008fe000282010085fffccf")) {
                    //关系统，标识未认证
                    inClass = false;
                    Bus.getInstance().emit("scene_event", "over_class");
                    handler.sendEmptyMessage(1001);
                    handler.sendEmptyMessageDelayed(1001, 800);
                } else if (code.equals("cffc0008fe000282010186fffccf")) {
                    //开系统
                    if (!inClass) {
                        //如果没有在上课中，延时发红外码
                        handler.sendEmptyMessageDelayed(1001, 2000);
                        handler.sendEmptyMessageDelayed(1001, 3500);
                        handler.sendEmptyMessageDelayed(1001, 5000);
                        handler.sendEmptyMessageDelayed(1001, 6500);
                    }
                    Bus.getInstance().emit("scene_event", "on_class");
                    inClass = true;
                } else if (code.equals("cffc0009fe0002680200016dfffccf")) {
                    //开投影或开大屏
                    Bus.getInstance().emit("scene_event", "screen_on");
                } else if (code.equals("cffc0009fe0002680200006cfffccf")) {
                    //关投影或关大屏
                    Bus.getInstance().emit("scene_event", "screen_off");
                }
                int targetCodeLen = parseInt(code.substring(6, 8), 16);
                int endInex = 0;
                if (8 + targetCodeLen * 2 <= code.length()) {
                    endInex = 8 + targetCodeLen * 2;
                } else {
                    endInex = code.length();
                }
                String targetCode = code.substring(8, endInex);
                //端口号：00  中控 01  刷卡器 02     ·电脑通讯 03  空调控制器 04  智能空开 05  控制面板 06HDMI矩阵  07红外转发器 08环境传感器 09 录播主机 0a电脑或平板
                String targetPort = code.substring(4, 6);
                String portType = null;
                if (targetPort.equals("01")) {
                    portType = "cardreader";
                } else if (targetPort.equals("02")) {
                    portType = "computer";
                    if (targetCode.equals("fe0102009a02f319ffff")) {
                        JSONObject params = new JSONObject();
                        Bus.getInstance().emit("exec_action", "close_comp", params, null, 5);
                    }

                } else if (targetPort.equals("03")) {
                    portType = "airctrl";
                } else if (targetPort.equals("04")) {
                    portType = "airpower";
                } else if (targetPort.equals("05")) {
                    portType = "controlpanel";
                } else if (targetPort.equals("06")) {
                    portType = "hdmimatrix";
                } else if (targetPort.equals("07")) {
                    portType = "infraredbus";
                } else if (targetPort.equals("08")) {
                    portType = "envsensor";
                } else if (targetPort.equals("09")) {
                    portType = "recordinghost";
                } else if (targetPort.equals("0a")) {
                    portType = "pctablet";

                } else if (targetPort.equals("0b")) {
                    portType = "switcher";
                } else if (targetPort.equals("0c")) {
                    portType = "outermatrix";
                    if (targetCode.startsWith("5357") && targetCode.length() >= 12) {
                        String[] nos = targetCode.substring(6, targetCode.length() - 4).split("20");
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("from", Integer.parseInt(nos[0]) - 30);
                        JSONArray jsonArray = new JSONArray();
                        for (int i = 1; i < nos.length; i++) {
                            jsonArray.add(Integer.parseInt(nos[i]) - 30);
                        }
                        jsonObject.put("to", jsonArray);
                        Message message1 = new Message();
                        message1.obj = JSON.toJSONString(jsonObject);
                        message1.what = 76;
                        handler.sendMessage(message1);

                    }
                } else if (targetPort.equals("0d")) {
                    portType = "debug";
                } else if (targetPort.equals("e0")) {
                    portType = "other1";
                } else if (targetPort.equals("e1")) {
                    portType = "other2";
                } else if (targetPort.equals("e2")) {
                    portType = "other3";
                } else if (targetPort.equals("e3")) {
                    portType = "other4";
                } else if (targetPort.equals("e4")) {
                    portType = "other5";
                } else if (targetPort.equals("e5")) {
                    portType = "other6";
                } else if (targetPort.equals("e6")) {
                    portType = "other7";
                } else if (targetPort.equals("e7")) {
                    portType = "other8";
                } else if (targetPort.equals("e8")) {
                    portType = "other9";
                } else if (targetPort.equals("e9")) {
                    portType = "other10";
                }
                sendCtrlSerialCode(portType, targetCode);

            } else if ((new RegExp("^fd[0-9a-f]{8,}efff$")).test(code)) {
                //空调控制器返回码，上传到服务器
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("action", "airctrl_setting_resp");
                jsonObject.put("code", code);
                jsonObject.put("type", "serial");
                jsonObject.put("dev_id", DeviceType.DEVICETYPE_CONTROLLER.toString());
                jsonObject.put("address", code.substring(2, 4));
                Bus.getInstance().emit("publish_feedback_msg", jsonObject);
            } else if ("fe0102009b01b288ffff".equals(code)) {
                sendCtrlSerialCode("computer", "fe0102009a02f319ffff");
            } else if (code.startsWith("fccccc") && code.endsWith("cccccf")) {
                String type = code.substring(6, 8);
                if (type.equals("01")) {
                    //控制设备
                    String contentHex = code.substring(8, code.length() - 6);
                    try {
                        JSONObject contentObj = JSON.parseObject(new String(HexUtil.hexToByteArray(contentHex)));
                        if (contentObj != null) {
                            Bus.getInstance().emit("exec_action", contentObj.getString("action"), contentObj.getJSONObject("params"), contentObj.getString("portType"), 5);
                        }
                    } catch (Exception e) {

                    }
                } else if (type.equals("02")) {
                    //同步时间
                    sendSerialMessageFromPath(portPath, "fccccc02" + HexUtil.bytesToHex(String.valueOf(System.currentTimeMillis()).getBytes()) + "cccccf");
                } else if (type.equals("03")) {
                    //请求认证方式
                    if (mContext == null) {
                        return;
                    }
                    String broadConfigStr = sharedPreferences.getString("broadConfig", null);
                    if (broadConfigStr != null) {
                        sendSerialMessageFromPath(portPath, "fccccc03" + HexUtil.bytesToHex(broadConfigStr.getBytes()) + "cccccf");
                    }
                }
                //ceee110000eeec
            } else if (code.startsWith("ceee") && code.endsWith("eeec")) {
                String type = code.substring(4, 6);
                boolean resend = false;
                if (code.substring(code.length() - 6, code.length() - 4).equals("01")) {
                    resend = false;
                }
                if (type.equals("01")) {
                    //面板向中控请求二维码动态参数
                    int unit = sharedPreferences.getInt("ctrl_unit", 0);
                    if (unit == 0) {
                        respBroadCode("ceee010200eeec", resend);
                        return;
                    }
                    if (roomInfo == null) {
                        respBroadCode("ceee010300eeec", resend);
                        return;
                    }
                    String qrParams = SignUtil.genDynamicQrParams(unit, roomInfo.getRoomId());
                    String lenHex = Integer.toHexString(qrParams.length() / 2);
                    if (lenHex.length() < 2) {
                        lenHex = "0" + lenHex;
                    }
                    respBroadCode("ceee0101" + lenHex + qrParams + "eeec", resend);
                } else if (type.equals("02")) {
                    String pwd = "";
                    String pwdHex = code.substring(8, code.length() - 4);
                    for (int i = 0; i < pwdHex.length() / 2; i++) {
                        pwd += String.valueOf(Integer.parseInt(pwdHex.substring(i * 2, (i + 1) * 2), 16));
                    }
                    if (roomInfo == null) {
                        respBroadCode("ceee020200eeec", resend);
                        return;
                    }
                    boolean result = SignUtil.checkDynamicPassword(roomInfo.getRoomId(), pwd);
                    if (result) {
                        respBroadCode("ceee020100eeec", resend);
                    } else {
                        String broadConfigStr = sharedPreferences.getString("broadConfig", null);
                        if (broadConfigStr == null || broadConfigStr.length() == 0) {
                            respBroadCode("ceee020000eeec", resend);
                        } else {
                            JSONObject broadConfig = JSON.parseObject(broadConfigStr);
                            if (broadConfig.containsKey("password1") && broadConfig.getString("password1").length() > 0 && pwd.equals(broadConfig.getString("password1"))) {
                                respBroadCode("ceee020100eeec", resend);
                                return;
                            }
                            if (broadConfig.containsKey("password2") && broadConfig.getString("password2").length() > 0 && pwd.equals(broadConfig.getString("password2"))) {
                                respBroadCode("ceee020100eeec", resend);
                                return;
                            }
                            respBroadCode("ceee020000eeec", resend);
                        }

                    }
                } else if (type.equals("03")) {
                    String broadConfigStr = sharedPreferences.getString("broadConfig", null);
                    //liuyong 判断是否是第一次进系统，并且是上课状态
                    if(code.equals("ceee03f000eeec")){
                        if(inClass){
                            respBroadCode("CEEE03F000EEEC", true);
                            return;
                        }
                    }
                    if (broadConfigStr == null || broadConfigStr.length() == 0) {
                        respBroadCode("CEEE030000EEEC", resend);
                    } else {
                        JSONObject broadConfig = JSON.parseObject(broadConfigStr);
                        if (broadConfig.getBooleanValue("lock")) {
                            String openType = broadConfig.getString("openType");
                            if ("1".equals(openType)) {
                                respBroadCode("ceee030100eeec", resend);
                            } else if ("2".equals(openType)) {
                                respBroadCode("ceee030200eeec", resend);
                            }
                        } else {
                            respBroadCode("ceee030000eeec", resend);
                        }
                    }
                    if (roomInfo != null && roomInfo.getRoomId() > 0) {
                        String nameHex = HexUtil.bytesToHex(roomInfo.getRoomName().getBytes());
                        if (nameHex.length() % 2 == 1) {
                            nameHex = "0" + nameHex;
                        }
                        sendCtrlSerialCode("controlpanel", "CEEE0B" + StringUtil.padNum(Integer.toHexString(7 + nameHex.length() / 2), 2).toUpperCase() + "00" + StringUtil.padNum(Integer.toHexString(roomInfo.getRoomId()), 6).toUpperCase() + nameHex + StringUtil.padNum(Integer.toHexString((int) (System.currentTimeMillis() / 1000)), 8).toUpperCase() + "EEEC", System.currentTimeMillis() + 1000);
                        return;
                    }

                } else if (type.equals("04")) {
                    //dzk 20231204 为了佛科注释
                    //上课状态
                   if (inClass) {
                        respBroadCode("CEEE040101EEEC", resend);
                    } else {
                        respBroadCode("CEEE040100EEEC", resend);
                    }
                } else if (type.equals("05")) {

                } else if (type.equals("06")) {
                    String subType = code.substring(8, 10);
                    if (subType.equals("00")) {
                        //关闭环境感知
                        sharedPreferences.edit().putBoolean("env_auto_ctrl", false).commit();
                    } else if (subType.equals("01")) {
                        //开启环境感知
                        sharedPreferences.edit().putBoolean("env_auto_ctrl", true).commit();
                    } else if (subType.equals("ff")) {
                        //查询是否开启
                        boolean autoCtrl = sharedPreferences.getBoolean("env_auto_ctrl", false);
                        if (autoCtrl) {
                            respBroadCode("ceee060101eeec", resend);
                        } else {
                            respBroadCode("ceee060100eeec", resend);
                        }
                    }
                } else if (type.equals("07")) {
                    int subType = Integer.parseInt(code.substring(8, 10), 16);
                    //CEEE07020001EEEC
                    String broadConfigStr = sharedPreferences.getString("c_setting_broadConfig", null);
                    switch (subType) {
                        case 0:
                            if (broadConfigStr != null) {
                                JSONObject broadSettingConfig = JSON.parseObject(broadConfigStr);
                                JSONObject lineObj = broadSettingConfig.getJSONObject("line");
                                StringBuffer sb = new StringBuffer();
                                boolean projectionTag = lineObj.getBooleanValue("projection");
                                if (projectionTag) {
                                    sb.append("0101");
                                }
                                boolean projectionScreenTag = lineObj.getBooleanValue("projectionScreen");
                                if (projectionScreenTag) {
                                    sb.append("0201");
                                }
                                boolean computerTag = lineObj.getBooleanValue("computer");
                                if (computerTag) {
                                    sb.append("0301");
                                }
                                boolean mikeControllerTag = lineObj.getBooleanValue("mikeController");
                                if (mikeControllerTag) {
                                    sb.append("0401");
                                }
                                boolean touchScreenTag = lineObj.getBooleanValue("touchScreen_teacher");
                                if (touchScreenTag) {
                                    sb.append("0501");
                                }
                                boolean touchScreenStudent = lineObj.getBooleanValue("touchScreen_student");
                                if (touchScreenStudent) {
                                    sb.append("0f01");
                                }
                                boolean touchScreenPlatform = lineObj.getBooleanValue("touchScreen_platform");
                                if (touchScreenPlatform) {
                                    sb.append("1001");
                                }
                                boolean irTag = lineObj.getBooleanValue("ir");
                                if (irTag) {
                                    sb.append("06");
                                    int tvNum = lineObj.getIntValue("tvNum");
                                    String numStr = Integer.toHexString(tvNum);
                                    if (numStr.length() < 2) {
                                        numStr = "0" + numStr;
                                    }
                                    sb.append(numStr);
                                }
                                boolean externalAmplifierTag = lineObj.getBooleanValue("externalAmplifier");
                                if (externalAmplifierTag) {
                                    sb.append("0701");
                                }
                                boolean externalAmplifierTag2 = lineObj.getBooleanValue("externalAmplifier2");
                                if (externalAmplifierTag2) {
                                    sb.append("1101");
                                }
                                JSONObject signalObj = broadSettingConfig.getJSONObject("signal");
                                if (signalObj != null) {
                                    int enableNum = 0;
                                    Set<String> keys = signalObj.keySet();
                                    Iterator<String> keysIterator = keys.iterator();
                                    while (keysIterator.hasNext()) {
                                        String key = keysIterator.next();
                                        String value = signalObj.getString(key);
                                        if (!value.equals("0")) {
                                            enableNum++;
                                        }
                                    }
                                    if (enableNum > 0) {
                                        String numStr = Integer.toHexString(enableNum);
                                        if (numStr.length() < 2) {
                                            numStr = "0" + numStr;
                                        }
                                        sb.append("08" + numStr);
                                    }
                                }


                                boolean tempControllerTag = lineObj.getBoolean("tempController");
                                int tempControllerNum = lineObj.getIntValue("tempControllerNum");
                                if (tempControllerTag) {
                                    String numStr = Integer.toHexString(tempControllerNum);
                                    if (numStr.length() < 2) {
                                        numStr = "0" + numStr;
                                    }
                                    sb.append("09" + numStr);
                                }
                                //liuyong
                                if(lineObj.containsKey("powerManager")){
                                    boolean powerEnable = lineObj.getBoolean("powerManager");
                                    int power = lineObj.getIntValue("powerManagerNum");
                                    if (powerEnable) {
                                        String numStr = Integer.toHexString(power);
                                        if (numStr.length() < 2) {
                                            numStr = "0" + numStr;
                                        }
                                        sb.append("12" + numStr);
                                    }
                                }

                                boolean recorderTag = lineObj.getBoolean("recorder");
                                if (recorderTag) {
                                    sb.append("0c01");
                                }
                                boolean envSensorTag = lineObj.getBoolean("envSensor");
                                if (envSensorTag) {
                                    sb.append("0d01");
                                }
                                boolean innerAmplifierTag = lineObj.getBoolean("innerAmplifier");
                                if (innerAmplifierTag) {
                                    sb.append("0e01");
                                }


                                int lightNum = 0;
                                int curtainNum = 0;
                                try {
                                    List<ZigbeeDevice> zigbeeDevices = DbUtil.getInstance().selector(ZigbeeDevice.class).findAll();
                                    if (zigbeeDevices != null) {
                                        for (ZigbeeDevice zigbeeDevice : zigbeeDevices) {
                                            if (zigbeeDevice.getDeviceType().startsWith("zigbee-switcher")) {
                                                String[] enableTags = zigbeeDevice.getEnableTag().split(",");
                                                for (int j = 0; j < enableTags.length; j++) {
                                                    if ("1".equals(enableTags[j])) {
                                                        lightNum = lightNum + 1;
                                                    }
                                                }

                                            }
                                            if (zigbeeDevice.getDeviceType().startsWith("zigbee-curtain")) {
                                                curtainNum = curtainNum + zigbeeDevice.getDevicekey().split(",").length;
                                            }
                                        }
                                    }

                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                                if (lightNum > 0) {
                                    String numStr = Integer.toHexString(lightNum);
                                    if (numStr.length() < 2) {
                                        numStr = "0" + numStr;
                                    }
                                    sb.append("0a" + numStr);
                                }
                                if (curtainNum > 0) {
                                    String numStr = Integer.toHexString(curtainNum);
                                    if (numStr.length() < 2) {
                                        numStr = "0" + numStr;
                                    }
                                    sb.append("0b" + numStr);
                                }
                                String lenHex = Integer.toHexString(sb.length() / 2 + 1);
                                if (lenHex.length() < 2) {
                                    lenHex = "0" + lenHex;
                                }
                                //ceee071100020103010501080409020c010a060b01eeec
                                String resultHex = "ceee07" + lenHex + "00" + sb.toString() + "eeec";
                                respBroadCode(resultHex, resend);
                            }
                            break;
                        case 1:
                            if (broadConfigStr != null) {
                                JSONObject broadSettingConfig = JSON.parseObject(broadConfigStr);
                                JSONObject signalObj = broadSettingConfig.getJSONObject("signal");
                                Set<String> keys = signalObj.keySet();
                                Iterator<String> keysIterator = keys.iterator();
                                StringBuffer stringBuffer = new StringBuffer();
                                while (keysIterator.hasNext()) {
                                    String key = keysIterator.next();
                                    String value = signalObj.getString(key);
                                    if (!value.equals("0")) {
                                        stringBuffer.append("0" + key.replace("signal", ""));
                                        stringBuffer.append("0" + Integer.toHexString(Integer.parseInt(value)));
                                    }
                                }
                                String lenHex = Integer.toHexString(stringBuffer.length() / 2 + 1);
                                if (lenHex.length() < 2) {
                                    lenHex = "0" + lenHex;
                                }
                                String resultHex = "ceee07" + lenHex + "01" + stringBuffer.toString() + "eeec";
                                respBroadCode(resultHex, resend);
                            }
                            break;
                        case 2:
                        case 3:
                            //灯窗信息查询
                            String queryLine = Integer.toString(Integer.parseInt(code.substring(10, 12), 16));
                            boolean enable = true;
                            String devName = "";
                            try {
                                List<ZigbeeDevice> zigbeeDevices = DbUtil.getInstance().selector(ZigbeeDevice.class).findAll();
                                for (ZigbeeDevice zigbeeDevice : zigbeeDevices) {
                                    if (zigbeeDevice.getDeviceType().startsWith((subType == 2 ? "zigbee-switcher" : "zigbee-curtain"))) {
                                        String deviceKey = zigbeeDevice.getDevicekey();
                                        String[] deviceKeys = deviceKey.split(",");
                                        for (int j = 0; j < deviceKeys.length; j++) {
                                            if (deviceKeys[j].equals(queryLine)) {
                                                String enableTag = zigbeeDevice.getEnableTag();
                                                String[] devNames = zigbeeDevice.getDeviceName().split(",");
                                                if (enableTag == null) {
                                                    enable = true;
                                                } else {
                                                    String[] enableTags = enableTag.split(",");
                                                    enable = "1".equals(enableTags[j]);
                                                }
                                                devName = devNames[j];
                                                break;
                                            }
                                        }

                                    }
                                }
                                if (subType == 2) {
                                    if (!devName.contains("灯")) {
                                        devName = devName + "灯";
                                    }
                                } else if (subType == 3) {
                                    if (!devName.contains("窗")) {
                                        devName = devName + "窗";
                                    }
                                }
                                StringBuffer stringBuffer = new StringBuffer();
                                //liuyong 如果名称等于空，直接返回
                                if("灯".equals(devName) || "窗".equals(devName)){
                                    break;
                                }
                                stringBuffer.append(code.substring(10, 12));
                                stringBuffer.append(enable ? "01" : "00");
                                stringBuffer.append(HexUtil.bytesToHex(devName.getBytes(StandardCharsets.UTF_8)));
                                String lenHex = Integer.toHexString(stringBuffer.length() / 2 + 1);
                                if (lenHex.length() < 2) {
                                    lenHex = "0" + lenHex;
                                }
                                String resultHex = "ceee07" + lenHex + "0" + subType + stringBuffer.toString() + "eeec";
                                respBroadCode(resultHex, resend);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                            break;
                        case 4:
                            if (broadConfigStr != null) {
                                JSONObject broadSettingConfig = JSON.parseObject(broadConfigStr);
                                JSONObject recorderObj = broadSettingConfig.getJSONObject("recorder");
                                StringBuffer sb = new StringBuffer();
                                boolean openPowerTag = recorderObj.getBooleanValue("openPower");
                                if (openPowerTag) {
                                    sb.append("01");
                                }
                                boolean closePowerTag = recorderObj.getBooleanValue("closePower");
                                if (closePowerTag) {
                                    sb.append("02");
                                }
                                boolean startRecordTag = recorderObj.getBooleanValue("startRecord");
                                if (startRecordTag) {
                                    sb.append("03");
                                }
                                boolean stopRecordTag = recorderObj.getBooleanValue("stopRecord");
                                if (stopRecordTag) {
                                    sb.append("04");
                                }
                                boolean pauseRecordTag = recorderObj.getBooleanValue("pauseRecord");
                                if (pauseRecordTag) {
                                    sb.append("05");
                                }
                                boolean autoDirecteTag = recorderObj.getBooleanValue("autoDirecte");
                                if (autoDirecteTag) {
                                    sb.append("06");
                                }
                                boolean manualDirecteTag = recorderObj.getBooleanValue("manualDirecte");
                                if (manualDirecteTag) {
                                    sb.append("07");
                                }
                                boolean teacherTag = recorderObj.getBooleanValue("teacher");
                                if (teacherTag) {
                                    sb.append("08");
                                }
                                boolean studentTag = recorderObj.getBooleanValue("student");
                                if (studentTag) {
                                    sb.append("09");
                                }
                                String lenHex = Integer.toHexString(sb.length() / 2 + 1);
                                if (lenHex.length() < 2) {
                                    lenHex = "0" + lenHex;
                                }
                                String resultHex = "ceee07" + lenHex + "04" + sb.toString() + "eeec";
                                respBroadCode(resultHex, resend);
                            }
                            break;
                        case 5:
                            String recorderConfigStr = sharedPreferences.getString("c_setting_recorderConfig", null);
                            if (recorderConfigStr != null) {
                                JSONObject recorderConfig = JSON.parseObject(recorderConfigStr);
                                StringBuffer sb = new StringBuffer();
                                String ctrlType = recorderConfig.getString("ctrl_type");
                                if ("broad_network".equals(ctrlType)) {
                                    sb.append("03");
                                } else if ("controller_serial".equals(ctrlType)) {
                                    sb.append("01");
                                } else if ("controller_network".equals(ctrlType)) {
                                    sb.append("02");
                                } else if ("broad_network".equals(ctrlType)) {
                                    sb.append("04");
                                }
                                sb.append("01");
                                String recorderHost = recorderConfig.getString("host");
                                String username = recorderConfig.getString("username");
                                String password = recorderConfig.getString("password");
                                String[] ipParts = recorderHost.split(".");
                                for (int i = 0; i < 4; i++) {
                                    sb.append(StringUtil.padNum(Integer.toHexString(Integer.parseInt(ipParts[i])), 2));
                                }
                                sb.append(StringUtil.padNum(Integer.toHexString(username.length()), 2));
                                char[] usernameChars = username.toCharArray();
                                for (int i = 0; i < usernameChars.length; i++) {
                                    sb.append(StringUtil.padNum(Integer.toHexString((int) usernameChars[i]), 2));
                                }
                                sb.append(StringUtil.padNum(Integer.toHexString(password.length()), 2));
                                char[] passwordChars = password.toCharArray();
                                for (int i = 0; i < passwordChars.length; i++) {
                                    sb.append(StringUtil.padNum(Integer.toHexString((int) passwordChars[i]), 2));
                                }
                                String lenHex = Integer.toHexString(sb.length() / 2 + 1);
                                if (lenHex.length() < 2) {
                                    lenHex = "0" + lenHex;
                                }
                                String resultHex = "ceee07" + lenHex + "05" + sb.toString() + "eeec";
                                respBroadCode(resultHex, resend);
                            }
                            break;
                        case 6:
                            if (broadConfigStr != null) {
                                JSONObject broadSettingConfig = JSON.parseObject(broadConfigStr);
                                JSONObject recorderObj = broadSettingConfig.getJSONObject("recorder");
                                StringBuffer sb = new StringBuffer();
                                boolean previewLivingVideo = recorderObj.getBooleanValue("previewLivingVideo");
                                if (previewLivingVideo) {
                                    sb.append("01");
                                } else {
                                    sb.append("00");
                                }
                                String lenHex = Integer.toHexString(sb.length() / 2 + 1);
                                if (lenHex.length() < 2) {
                                    lenHex = "0" + lenHex;
                                }
                                String resultHex = "ceee07" + lenHex + "06" + sb.toString() + "eeec";
                                respBroadCode(resultHex, resend);
                            }
                            break;
                    }
                } else if (type.equals("08")) {
                    String recorderConfig = sharedPreferences.getString("c_setting_recorderConfig", null);
                    String ctrlType = "serial";
                    JSONObject recorderConfigObj = null;
                    if (recorderConfig != null) {
                        try {
                            recorderConfigObj = JSON.parseObject(recorderConfig);
                            if (recorderConfigObj != null) {
                                ctrlType = recorderConfigObj.getString("ctrl_type");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                    if ("controller_serial".equals(ctrlType)) {
                        String resultHex = "CEEE0803";
                        //工作状态
                        if ("on".equals(recorderStatus[0])) {
                            resultHex += "01";
                        } else {
                            resultHex += "00";
                        }
                        //直播状态
                        if ("on".equals(recorderStatus[1])) {
                            resultHex += "01";
                        } else {
                            resultHex += "00";
                        }
                        //录制状态
                        if ("on".equals(recorderStatus[2])) {
                            resultHex += "02";
                        } else if ("pause".equals(recorderStatus[2])) {
                            resultHex += "01";
                        } else {
                            resultHex += "00";
                        }
                        resultHex += "EEEC";
                        respBroadCode(resultHex, resend);
                    } else if ("controller_network".equals(ctrlType)) {
                        RecorderApi.queryRecorderStatus(recorderConfigObj, new RecorderApi.OnRecorderStatusReturn() {
                            @Override
                            public void onGotRecorderStatus(int[] status) {
                                if (status != null) {
                                    String resultHex = "CEEE0803";
                                    resultHex += ("0" + status[0]);
                                    resultHex += ("0" + status[1]);
                                    resultHex += ("0" + status[2]);
                                    resultHex += "EEEC";
                                    respBroadCode(resultHex, false);
                                    recorderStatus[0] = status[0] == 1 ? "on" : "off";
                                    recorderStatus[1] = status[1] == 1 ? "on" : "off";
                                    if (status[2] == 0) {
                                        recorderStatus[2] = "off";
                                    } else if (status[2] == 1) {
                                        recorderStatus[2] = "pause";
                                    } else if (status[2] == 2) {
                                        recorderStatus[2] = "on";
                                    }

                                }

                            }
                        });
                    }
                } else if (type.equals("0d")) {
                    if(code.length()>18){
                        Message message = new Message();
                        message.what = 9999;
                        try{
                            String card = String.valueOf(Long.parseLong(code.substring(10, 18), 16));
                            while (card.length() < 10) {
                                card = "0" + card;
                            }
                            message.obj = card;
                            handler.sendMessage(message);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                } else if (type.equals("0e")) {
                    Message message = new Message();
                    message.what = 9998;
                    handler.sendMessage(message);
                } else if (type.equals("0f")) {
                    //矩阵控制
                    String videoSignalConfig = sharedPreferences.getString("c_setting_videoSignal", null);
                    String signalPortType = "1";
                    if (videoSignalConfig != null) {
                        JSONObject videoSignalConfigObj = JSON.parseObject(videoSignalConfig);
                        signalPortType = videoSignalConfigObj.getString("signal_type");
                    }
                    String singleSwitchStr = null;
                    long voiceDelay = 2000;
                    //输入端口号
                    int inputNO = Integer.parseInt(code.substring(10, 12), 16);
                    String outputArrHex = code.substring(14, code.length() - 4);
                    int outputNum = outputArrHex.length() / 2;
                    //输出端口
                    int[] arr = new int[outputNum];
                    for (int i = 0; i < outputNum; i++) {
                        arr[i] = Integer.parseInt(outputArrHex.substring(2 * i, 2 * (i + 1)), 16);
                    }
                    switch (Integer.parseInt(signalPortType)) {
                        case 0:
                            //4进4出HDMI
                            singleSwitchStr = String.valueOf(inputNO) + "B";
                            for (int i = 0; i < arr.length; i++) {
                                singleSwitchStr += String.valueOf(arr[i]);
                                if (i != arr.length - 1) {
                                    singleSwitchStr += ",";
                                }
                            }
                            singleSwitchStr += ".";
                            break;
                        case 2:
                            //8进8出HDMI
                            singleSwitchStr = String.valueOf(inputNO) + "B";
                            for (int i = 0; i < arr.length; i++) {
                                singleSwitchStr += String.valueOf(arr[i]);
                                if (i != arr.length - 1) {
                                    singleSwitchStr += ",";
                                }
                            }
                            singleSwitchStr += ".";
                            voiceDelay = 6000;
                            break;
                        case 3:
                            //4进VGA/HDMI混合，4出HDMI
                            switch (inputNO) {
                                case 1:
                                    singleSwitchStr = "1ALL.";
                                    break;
                                case 2:
                                    singleSwitchStr = "3ALL.";
                                    break;
                                case 3:
                                    singleSwitchStr = "4ALL.";
                                    break;
                                case 4:
                                    singleSwitchStr = "2ALL.";
                                    break;
                            }
                            voiceDelay = 3000;
                            break;
                    }
                    if (singleSwitchStr != null) {
                        sendCtrlSerialCode(HDMIMATRIX, HexUtil.Str2SerialHex(singleSwitchStr), System.currentTimeMillis());
                        sendCtrlSerialCode(null, "FE 00 02 86 02 00 03 8D FF", System.currentTimeMillis() + voiceDelay);
                        //发送联动码
                        //自定义情景
                        String bSceneConfigStr = sharedPreferences.getString("c_setting_sceneConfig", null);
                        if (bSceneConfigStr == null) {
                            return;
                        }
                        JSONObject bSceneConfig = JSON.parseObject(bSceneConfigStr);
                        JSONArray customScenes = bSceneConfig.getJSONArray("customScenes");
                        if (customScenes != null && customScenes.size() > 0) {
                            for (int k = 0; k < customScenes.size(); k++) {
                                JSONObject customScene = customScenes.getJSONObject(k);
                                if (("HDMI" + inputNO).equals(customScene.getString("key"))) {
                                    JSONArray sActions = customScene.getJSONArray("actions");
                                    for (int i = 0; i < sActions.size(); i++) {
                                        JSONObject sceneAction = sActions.getJSONObject(i);
                                        if (!sceneAction.containsKey("key")) {
                                            continue;
                                        }
                                        String key = sceneAction.getString("key");
                                        String serialPortType = null;
                                        if (sceneAction.containsKey("portType")) {
                                            serialPortType = sceneAction.getString("portType");
                                        }
                                        int delay = 0;
                                        if (sceneAction.containsKey("delay")) {
                                            delay = sceneAction.getIntValue("delay");
                                        }
                                        if ("custom".equals(key)) {
                                            sendCtrlSerialCode(serialPortType, sceneAction.getString("code"), System.currentTimeMillis() + delay);
                                        } else {
                                            if (defaultActionCodeMap.containsKey(key)) {
                                                sendCtrlSerialCode(serialPortType, defaultActionCodeMap.get(key), System.currentTimeMillis() + delay);
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                } else if (type.equals("10")) {
                    String h = Long.toString(System.currentTimeMillis() / 1000, 16);
                    while (h.length() < 8) {
                        h = "0" + h;
                    }
                    respBroadCode("CEEE100400" + h.toUpperCase() + "EEEC", false);
                } else if (type.equals("11")) {
                    String overClassPowerDelayConfig = sharedPreferences.getString("c_setting_overClassPowerDelay", null);
                    JSONObject overClassPowerDelayConfigObj = null;
                    int delay = 40;
                    if (overClassPowerDelayConfig != null) {
                        try {
                            overClassPowerDelayConfigObj = JSON.parseObject(overClassPowerDelayConfig);
                            if (overClassPowerDelayConfigObj != null && overClassPowerDelayConfigObj.containsKey("shutdown_delay")) {
                                delay = overClassPowerDelayConfigObj.getIntValue("shutdown_delay") + 12;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    String h = Integer.toString(delay, 16);
                    if (h.length() < 2) {
                        h = "0" + h;
                    }
                    respBroadCode("CEEE110100" + h.toUpperCase() + "EEEC", false);
                }
                //dzk 20231120 添加管理员密码判断
                else if (type.equals("a1")) {
                    String pwd = "";
                    String pwdHex = code.substring(8, code.length() - 4);
                    for (int i = 0; i < pwdHex.length() / 2; i++) {
                        pwd += String.valueOf(Integer.parseInt(pwdHex.substring(i * 2, (i + 1) * 2), 16));
                    }
                    if (roomInfo == null) {
                        respBroadCode("ceee020200eeec", resend);
                        return;
                    }


                    String broadConfigStr = sharedPreferences.getString("broadConfig", null);
                    if (broadConfigStr == null || broadConfigStr.length() == 0) {
                        respBroadCode("ceee020000eeec", resend);
                    } else {
                        JSONObject broadConfig = JSON.parseObject(broadConfigStr);
                        if (broadConfig.containsKey("password3") && broadConfig.getString("password3").length() > 0 && pwd.equals(broadConfig.getString("password3"))) {
                            respBroadCode("ceee020100eeec", resend);
                            return;
                        }

                        respBroadCode("ceee020000eeec", resend);
                    }


                }
            }

        }
        //liuyong 传感器转发到串口面板
        else if("envsensor".equals(portName)){
            sendCtrlSerialCode("controlpanel", code);
        } else if ("computer".equals(portName)) {
            if (code.equals("fe0102009b01b288ffff")) {
                //立即下课
                //取消定时器
//                if(confirmTimer){
//                    clearTimeout(confirmTimer)
//                    confirmTimer=null
//                }.
//                //执行下课指令
//                bus.emit('exec_action', 'over_class')
            } else if (code.equals("fe0102009f01b048ffff")) {
                //拔卡延堂5分钟，直接关机
                //返回电脑确认收到延堂指令
//                if( serialPortMap[portPath]&&serialPortMap[portPath].isOpen()){
//                    serialPortMap[portPath].sendCode('FE0102009FFF31CBFFFF');
//                }
//                if(confirmTimer){
//                    clearTimeout(confirmTimer)
//                    confirmTimer=null
//                }
//                if(delayClassTimer){
//                    clearTimeout(delayClassTimer);
//                    delayClassTimer=null;
//                }
//                delayClassTimer=setTimeout(function(){
//                    bus.emit('exec_action', 'over_class')
//                },300000)
            } else if (code.equals("fe0102009f02f049ffff")) {
                //定时下课延堂5分钟，再次确认关机
                //返回电脑确认收到延堂指令
//                if( serialPortMap[portPath]&&serialPortMap[portPath].isOpen()){
//                    serialPortMap[portPath].sendCode("FE0102009FFF31CBFFFF");
//                }
//                if(confirmTimer){
//                    clearTimeout(confirmTimer)
//                    confirmTimer=null
//                }
//                if(delayClassTimer){
//                    clearTimeout(delayClassTimer);
//                    delayClassTimer=null;
//                }
//                delayClassTimer=setTimeout(function(){
//                    for (var port in serialportConfigMap) {
//                        if (serialportConfigMap[port] === "computer") {
//                            //弹窗确认关机
//                            serialPortMap[port].sendCode('FE0102009B02F289FFFF');
//                        }
//                    }
//                },300000)
            }
        }
        if ("cffc0f08fe00020901010dfffccf".equals(code)) {
            //12V通电
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PH0/data");
        } else if ("cffc0f08fe00020901000cfffccf".equals(code)) {
            //12V断电
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PH0/data");
        } else if ("cffc0f08fe00020902010efffccf".equals(code)) {
            //5V通电
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PB15/data");
        } else if ("cffc0f08fe00020902000dfffccf".equals(code)) {
            //5V断电
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PB15/data");
        } else if ("cffc0f08fe00020903010ffffccf".equals(code)) {
            //备用1高电平
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PB16/data");
        } else if ("cffc0f08fe00020903000efffccf".equals(code)) {
            //备用1低电平
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PB16/data");
        } else if ("cffc0f08fe000209040110fffccf".equals(code)) {
            //备用2高电平
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PB17/data");
        } else if ("cffc0f08fe00020904000ffffccf".equals(code)) {
            //备用2低电平
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PB17/data");
        } else if (code.startsWith("fddddd") && code.endsWith("dddddf") && code.length() == 22) {
            int actionTag = Integer.parseInt(code.substring(6, 8), 16);
            int params1 = Integer.parseInt(code.substring(8, 10), 16);
            int params2 = Integer.parseInt(code.substring(10, 12), 16);
            int params3 = Integer.parseInt(code.substring(12, 14), 16);
            int params4 = Integer.parseInt(code.substring(14, 16), 16);
            String action = null;
            String portType = null;
            JSONObject params = new JSONObject();
            String broadSceneConfig = sharedPreferences.getString("c_setting_sceneConfig", null);
            switch (actionTag) {
                case 0:
                    //中控控制
                    if (broadSceneConfig == null) {
                        if (params1 == 1) {
                            action = "in_class";
                        } else if (params1 == 0) {
                            action = "over_class";
                        }
                    } else {
                        JSONObject broadSceneConfigObj = JSON.parseObject(broadSceneConfig);
                        if (broadSceneConfigObj.containsKey("enable") && broadSceneConfigObj.getBoolean("enable")) {
                            if (params1 == 1) {
                                //上课
                                JSONArray onClassActions = broadSceneConfigObj.getJSONArray("onClassActions");
                                for (int i = 0; i < onClassActions.size(); i++) {
                                    JSONObject sceneAction = onClassActions.getJSONObject(i);
                                    String serialPortType = sceneAction.getString("portType");
                                    String key = sceneAction.getString("key");
                                    int delay = sceneAction.getIntValue("delay");
                                    if ("custom".equals(key)) {
                                        sendCtrlSerialCode(serialPortType, sceneAction.getString("code"), System.currentTimeMillis() + delay);
                                    } else {
                                        if (defaultActionCodeMap.containsKey(key)) {
                                            sendCtrlSerialCode(serialPortType, defaultActionCodeMap.get(key), System.currentTimeMillis() + delay);
                                        }

                                    }
                                }
                                String videoSignalConfig = sharedPreferences.getString("c_setting_videoSignal", null);
                                String signalType = "0";
                                String initOutput = "1";
                                int defaultDaly = 20;

                                if (videoSignalConfig != null) {
                                    JSONObject videoSignalConfigObj = JSON.parseObject(videoSignalConfig);
                                    signalType = videoSignalConfigObj.getString("signal_type");
                                    initOutput = videoSignalConfigObj.getString("init_output");
                                    if (videoSignalConfigObj.containsKey("switch_delay")) {
                                        defaultDaly = videoSignalConfigObj.getIntValue("switch_delay");
                                    }
                                }
                                String singleSwitchSerialCode = null;
                                String singleSwitchSerialPort = null;
                                long voiceDelay = 2000;
                                //liuyong 判断没有设置初始信号源时默认发送切换第一路
                                if(null == initOutput){
                                    initOutput = "1";
                                }
                                switch (Integer.parseInt(signalType)) {
                                    case 0:
                                        //4进4出HDMI
                                        singleSwitchSerialPort = HDMIMATRIX;
                                        singleSwitchSerialCode = "3" + initOutput + "414C4C2E";
                                        break;
                                    case 1:
                                        //4进4出VGA
                                        switch (Integer.parseInt(initOutput)) {
                                            case 1:
                                                singleSwitchSerialCode = "FE 00 02 86 02 00 04 8E FF";
                                                break;
                                            case 2:
                                                singleSwitchSerialCode = "FE 00 02 86 02 00 05 8F FF";
                                                break;
                                            case 3:
                                                singleSwitchSerialCode = "FE 00 02 86 02 00 02 8C FF";
                                                break;
                                            case 4:
                                                singleSwitchSerialCode = "FE 00 02 86 02 00 03 8D FF";
                                                break;
                                        }
                                        break;
                                    case 2:
                                        //8进8出HDMI
                                        singleSwitchSerialPort = HDMIMATRIX;
                                        singleSwitchSerialCode = "3" + initOutput + "42312C322C332C342C352C362C372C382E";
                                        voiceDelay = 6000;
                                        break;
                                    case 3:
                                        //4进VGA/HDMI混合，4出HDMI
                                        singleSwitchSerialPort = HDMIMATRIX;
                                        switch (Integer.parseInt(initOutput)) {
                                            case 1:
                                                singleSwitchSerialCode = "31414C4C2E";
                                                break;
                                            case 2:
                                                singleSwitchSerialCode = "33414C4C2E";
                                                break;
                                            case 3:
                                                singleSwitchSerialCode = "34414C4C2E";
                                                break;
                                            case 4:
                                                singleSwitchSerialCode = "32414C4C2E";
                                                break;
                                        }
                                        break;

                                }
                                if (singleSwitchSerialCode != null) {
                                    sendCtrlSerialCode(singleSwitchSerialPort, singleSwitchSerialCode, System.currentTimeMillis() + defaultDaly * 1000);
                                    sendCtrlSerialCode(null, "FE 00 02 86 02 00 03 8D FF", System.currentTimeMillis() + defaultDaly * 1000 + voiceDelay);
                                }


                            } else if (params1 == 0) {
                                JSONArray overClassActions = broadSceneConfigObj.getJSONArray("overClassActions");
                                for (int i = 0; i < overClassActions.size(); i++) {
                                    JSONObject sceneAction = overClassActions.getJSONObject(i);
                                    String serialPortType = sceneAction.getString("portType");
                                    String key = sceneAction.getString("key");
                                    int delay = sceneAction.getIntValue("delay");
                                    if ("custom".equals(key)) {
                                        sendCtrlSerialCode(serialPortType, sceneAction.getString("code"), System.currentTimeMillis() + delay);
                                    } else {
                                        if (defaultActionCodeMap.containsKey(key)) {
                                            sendCtrlSerialCode(serialPortType, defaultActionCodeMap.get(key), System.currentTimeMillis() + delay);
                                        }

                                    }
                                }
                            }
                        } else {
                            if (params1 == 1) {
                                action = "in_class";
                            } else if (params1 == 0) {
                                action = "over_class";
                            }
                        }

                    }

                    break;
                case 1:
                    //灯控制
                    portType = "ZIGBEE";
                    JSONArray jsonArray = new JSONArray();
                    if (params1 == 225) {
                        action = "open_light";
                        for (int i = 1; i <= 12; i++) {
                            jsonArray.add(i);
                        }
                    } else if (params1 == 224) {
                        action = "close_light";
                        for (int i = 1; i <= 12; i++) {
                            jsonArray.add(i);
                        }
                    } else {
                        if (params1 == 1) {
                            action = "open_light";
                        } else if (params1 == 0) {
                            action = "close_light";
                        }
                        jsonArray.add(params2);
                    }
                    params.put("location", jsonArray);
                    break;
                case 2:
                    //窗控制
                    portType = "ZIGBEE";
                    JSONArray cuArr = new JSONArray();
                    if (params1 == 225) {
                        action = "window_open";
                        for (int i = 1; i <= 12; i++) {
                            cuArr.add(i);
                        }
                    } else if (params1 == 224) {
                        action = "window_close";
                        for (int i = 1; i <= 12; i++) {
                            cuArr.add(i);
                        }
                    } else if (params1 == 226) {
                        action = "stop_rotate";
                        for (int i = 1; i <= 12; i++) {
                            cuArr.add(i);
                        }
                    } else {
                        if (params1 == 1) {
                            action = "window_open";
                        } else if (params1 == 0) {
                            action = "window_close";
                        } else if (params1 == 2) {
                            action = "stop_rotate";
                        }
                        cuArr.add(params2);
                    }
                    params.put("location", cuArr);
                    break;
                case 3:
                    //检测是否允许控空调  1温度范围  2时段限制
                    //空调控制
                    portType = "airctrl";
                    //空调编号
                    JSONArray acArr = new JSONArray();
                    //温度
                    JSONArray acArr2 = new JSONArray();
                    //风速
                    JSONArray acArr3 = new JSONArray();
                    acArr.add(params2);
                    if (params1 == 255) {
                        //开空调继电器
                        action = "open_airctrl_switcher";
                    } else if (params1 == 254) {
                        //关空调继电器
                        action = "close_airctrl_switcher";
                    } else {
                        if (params1 == 2) {
                            //制热
                            action = "set_airctrl_temprature";
                            acArr2.add(params3);
                            acArr3.add(params4);
                            params.put("temperature", acArr2);
                            JSONArray mArr = new JSONArray();
                            mArr.add(params1);
                            params.put("mode", mArr);
                            params.put("speed", acArr3);
                        } else if (params1 == 1) {
                            //制冷
                            action = "set_airctrl_temprature";
                            acArr2.add(params3);
                            acArr3.add(params4);
                            params.put("temperature", acArr2);
                            JSONArray mArr = new JSONArray();
                            mArr.add(params1);
                            params.put("mode", mArr);
                            params.put("speed", acArr3);
                        } else if (params1 == 0) {
                            //关空调
                            action = "close_airctrl";
                            acArr2.add(0);
                            params.put("power", acArr2);
                        }
                    }
                    params.put("location", acArr);
                    JSONObject zigbeeObj = new JSONObject();
                    zigbeeObj.put("action", action);
                    zigbeeObj.put("paramsObj", params);
                    JSONArray zigbeeDevs = new JSONArray();
                    zigbeeDevs.add("airctrl-zigbee-leectrl");
                    zigbeeObj.put("devType", zigbeeDevs);
                    Bus.getInstance().emit("ctrl_zigbee", zigbeeObj);
                    break;
                case 4:
                    //录播控制
                    String recorderConfig = sharedPreferences.getString("c_setting_recorderConfig", null);
                    String ctrlType = "controller_serial";
                    JSONObject recorderConfigObj = null;
                    if (recorderConfig != null) {
                        try {
                            recorderConfigObj = JSON.parseObject(recorderConfig);
                            if (recorderConfigObj != null) {
                                ctrlType = recorderConfigObj.getString("ctrl_type");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                    if ("controller_serial".equals(ctrlType)) {
                        portType = "recordinghost";
                        String recorderSerialConfig = sharedPreferences.getString("c_setting_recorderSerialConfig", null);
                        if (recorderSerialConfig == null) {
                            switch (params1) {
                                case 1:
                                    action = "start_record";
                                    break;
                                case 2:
                                    action = "pause_record";
                                    break;
                                case 3:
                                    action = "stop_record";
                                    break;
                                case 4:
                                    action = "open_recorder_power";
                                    break;
                                case 5:
                                    action = "close_recorder_power";
                                    break;
                                case 6:
                                    action = "start_living";
                                    break;
                                case 7:
                                    action = "stop_living";
                                    break;
                            }
                        } else {
                            JSONObject recorderSerialConfigObj = JSON.parseObject(recorderSerialConfig);
                            switch (params1) {
                                case 1:
                                    sendCtrlSerialCode(portType, recorderSerialConfigObj.getString("start_record"));
                                    break;
                                case 2:
                                    sendCtrlSerialCode(portType, recorderSerialConfigObj.getString("pause_record"));
                                    break;
                                case 3:
                                    sendCtrlSerialCode(portType, recorderSerialConfigObj.getString("stop_record"));
                                    break;
                                case 4:
                                    sendCtrlSerialCode(portType, recorderSerialConfigObj.getString("open_power"));
                                    break;
                                case 5:
                                    sendCtrlSerialCode(portType, recorderSerialConfigObj.getString("close_power"));
                                    break;
                                case 6:
                                    sendCtrlSerialCode(portType, recorderSerialConfigObj.getString("start_living"));
                                    break;
                                case 7:
                                    sendCtrlSerialCode(portType, recorderSerialConfigObj.getString("stop_living"));
                                    break;
                            }
                        }

                    } else if ("controller_network".equals(ctrlType)) {
                        switch (params1) {
                            case 1:
                                RecorderApi.startRecord(recorderConfigObj);
                                break;
                            case 2:
                                if ("pause".equals(recorderStatus[2])) {
                                    RecorderApi.continueRecord(recorderConfigObj);
                                } else {
                                    RecorderApi.pauseRecord(recorderConfigObj);
                                }
                                break;
                            case 3:
                                RecorderApi.stopRecord(recorderConfigObj);
                                break;
                            case 4:
                                RecorderApi.recorderPowerSwitch(recorderConfigObj, true);
                                break;
                            case 5:
                                RecorderApi.recorderPowerSwitch(recorderConfigObj, false);
                                break;
                            case 6:
                                RecorderApi.livingSwitch(recorderConfigObj, true);
                                break;
                            case 7:
                                RecorderApi.livingSwitch(recorderConfigObj, false);
                                break;
                        }
                    }

                    break;
                case 5:
                    //投影控制
                    portType = null;
                    switch (params2) {
                        case 1:
                            switch (params1) {
                                case 1:
                                    action = "cast_open";
                                    break;
                                case 0:
                                    action = "cast_close";
                                    break;
                            }
                            break;
                        case 2:
                            switch (params1) {
                                case 1:
                                    action = "group_screen_on";
                                    break;
                                case 0:
                                    action = "group_screen_off";
                                    break;
                            }
                            break;
                    }

                    break;
                case 6:
                    //幕布控制
                    portType = null;
                    switch (params1) {
                        case 1:
                            action = "cloth_down";
                            break;
                        case 0:
                            action = "cloth_up";
                            break;
                    }
                    break;
                case 7:
                    //功放音量控制
                    portType = "amplifier";
                    action = "mic_volume";
                    params.put("value", params2);
                    break;
                case 8:
                    //教师屏控制
                    portType = null;
                    switch (params1) {
                        case 1:
                            action = "teacher_screen_on";
                            break;
                        case 0:
                            action = "teacher_screen_off";
                            break;
                    }
                    break;
                case 9:
                    //小组屏控制
                    portType = null;
                    switch (params1) {
                        case 1:
                            action = "group_screen_on";
                            break;
                        case 0:
                            action = "group_screen_off";
                            break;
                    }
                    break;
                case 10:
                    //时序电源
                    portType = "other3";
                    switch (params1) {
                        case 1:
                            action = "timer_power_on";
                            break;
                        case 0:
                            action = "timer_power_off";
                            break;
                    }
                    break;
                case 11:
                    //无线麦
                    portType = "other1";
                    action = "mike_charge_box_on";
                    break;
                case 12:
                    //IO控制
                    action = null;
                    switch (params1) {
                        case 0:
                            switch (params2) {
                                case 1:
                                    TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PB16/data");
                                    break;
                                case 2:
                                    TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PB17/data");
                                    break;
                            }
                            break;
                        case 1:
                            switch (params2) {
                                case 1:
                                    TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PB16/data");
                                    break;
                                case 2:
                                    TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PB17/data");
                                    break;
                            }
                            break;
                    }
                    break;
                case 13:
                    //信源切换
                    String broadConfigStr = sharedPreferences.getString("c_setting_broadConfig", null);
                    if (broadConfigStr != null) {
                        JSONObject broadSettingConfig = JSON.parseObject(broadConfigStr);
                        JSONObject signalObj = broadSettingConfig.getJSONObject("signal");
                        Set<String> keys = signalObj.keySet();
                        Iterator<String> keysIterator = keys.iterator();
                        //输出接口序号
                        int signalPort = 1;
                        String signalType = String.valueOf(params2);
                        while (keysIterator.hasNext()) {
                            String key = keysIterator.next();
                            String value = signalObj.getString(key);
                            if (signalType.equals(value)) {
                                signalPort = Integer.parseInt(key.substring(6));
                                break;
                            }
                        }
                        String videoSignalConfig = sharedPreferences.getString("c_setting_videoSignal", null);
                        String signalPortType = "1";
                        if (videoSignalConfig != null) {
                            JSONObject videoSignalConfigObj = JSON.parseObject(videoSignalConfig);
                            signalPortType = videoSignalConfigObj.getString("signal_type");
                        }
                        String singleSwitchSerialCode = null;
                        String singleSwitchSerialPort = null;
                        JSONObject broadSceneConfigObj = null;
                        if (broadSceneConfig != null) {
                            broadSceneConfigObj = JSON.parseObject(broadSceneConfig);
                        }
                        long voiceDelay = 2000;
                        //矩阵类型
                        switch (Integer.parseInt(signalPortType)) {
                            case 0:
                                //4进4出HDMI
                                singleSwitchSerialPort = HDMIMATRIX;
                                singleSwitchSerialCode = "3" + signalPort + "414C4C2E";
                                break;
                            case 1:
                                //4进4出VGA
                                switch (signalPort) {
                                    case 1:
                                        singleSwitchSerialCode = "FE 00 02 86 02 00 04 8E FF";
                                        break;
                                    case 2:
                                        singleSwitchSerialCode = "FE 00 02 86 02 00 05 8F FF";
                                        break;
                                    case 3:
                                        singleSwitchSerialCode = "FE 00 02 86 02 00 02 8C FF";
                                        break;
                                    case 4:
                                        singleSwitchSerialCode = "FE 00 02 86 02 00 03 8D FF";
                                        break;
                                }
                                break;
                            case 2:
                                //8进8出HDMI

                                singleSwitchSerialPort = HDMIMATRIX;
                                singleSwitchSerialCode = "3" + signalPort + "42312C322C332C342C352C362C372C382E";
                                voiceDelay = 6000;

                                break;
                            case 3:
                                //4进VGA/HDMI混合，4出HDMI

                                singleSwitchSerialPort = HDMIMATRIX;
                                switch (signalPort) {
                                    case 1:
                                        singleSwitchSerialCode = "31414C4C2E";
                                        break;
                                    case 2:
                                        singleSwitchSerialCode = "33414C4C2E";
                                        break;
                                    case 3:
                                        singleSwitchSerialCode = "34414C4C2E";
                                        break;
                                    case 4:
                                        singleSwitchSerialCode = "32414C4C2E";
                                        break;
                                }

                                break;

                        }
                        if (singleSwitchSerialCode != null) {
                            boolean sendDefault = false;
                            switch (params2) {
                                case 2:
                                    if (broadSceneConfigObj == null || (!(broadSceneConfigObj.containsKey("sendLaptopDefaultCode"))) || broadSceneConfigObj.getBoolean("sendLaptopDefaultCode")) {
                                        sendDefault = true;
                                    }
                                    break;
                                case 3:
                                    if (broadSceneConfigObj == null || (!(broadSceneConfigObj.containsKey("sendPcDefaultCode"))) || broadSceneConfigObj.getBoolean("sendPcDefaultCode")) {
                                        sendDefault = true;
                                    }
                                    break;
                                case 5:
                                    if (broadSceneConfigObj == null || (!(broadSceneConfigObj.containsKey("sendBroadcastDefaultCode"))) || broadSceneConfigObj.getBoolean("sendBroadcastDefaultCode")) {
                                        sendDefault = true;
                                    }
                                    break;
                                case 6:
                                    if (broadSceneConfigObj == null || (!(broadSceneConfigObj.containsKey("sendRecorderDefaultCode"))) || broadSceneConfigObj.getBoolean("sendRecorderDefaultCode")) {
                                        sendDefault = true;
                                    }
                                    break;
                                default:
                                    sendDefault = true;
                                    break;
                            }
                            if (sendDefault) {
                                sendCtrlSerialCode(singleSwitchSerialPort, singleSwitchSerialCode, System.currentTimeMillis());
                                sendCtrlSerialCode(null, "FE 00 02 86 02 00 03 8D FF", System.currentTimeMillis() + voiceDelay);
                            }

                        }
                        if (broadSceneConfigObj != null) {
                            if ("3".equals(signalType) && broadSceneConfigObj.containsKey("showPcActions")) {
                                JSONArray showPcActions = broadSceneConfigObj.getJSONArray("showPcActions");
                                for (int i = 0; i < showPcActions.size(); i++) {
                                    JSONObject sceneAction = showPcActions.getJSONObject(i);
                                    String serialPortType = sceneAction.getString("portType");
                                    String key = sceneAction.getString("key");
                                    int delay = sceneAction.getIntValue("delay");
                                    if ("custom".equals(key)) {
                                        sendCtrlSerialCode(serialPortType, sceneAction.getString("code"), System.currentTimeMillis() + delay);
                                    } else {
                                        if (defaultActionCodeMap.containsKey(key)) {
                                            sendCtrlSerialCode(serialPortType, defaultActionCodeMap.get(key), System.currentTimeMillis() + delay);
                                        }
                                    }
                                }

                            } else if ("2".equals(signalType) && broadSceneConfigObj.containsKey("showLaptopActions")) {
                                JSONArray showLaptopActions = broadSceneConfigObj.getJSONArray("showLaptopActions");
                                for (int i = 0; i < showLaptopActions.size(); i++) {
                                    JSONObject sceneAction = showLaptopActions.getJSONObject(i);
                                    String serialPortType = sceneAction.getString("portType");
                                    String key = sceneAction.getString("key");
                                    int delay = sceneAction.getIntValue("delay");
                                    if ("custom".equals(key)) {
                                        sendCtrlSerialCode(serialPortType, sceneAction.getString("code"), System.currentTimeMillis() + delay);
                                    } else {
                                        if (defaultActionCodeMap.containsKey(key)) {
                                            sendCtrlSerialCode(serialPortType, defaultActionCodeMap.get(key), System.currentTimeMillis() + delay);
                                        }
                                    }
                                }

                            } else if ("5".equals(signalType) && broadSceneConfigObj.containsKey("showBroadcastActions")) {
                                JSONArray showBroadcastActions = broadSceneConfigObj.getJSONArray("showBroadcastActions");
                                for (int i = 0; i < showBroadcastActions.size(); i++) {
                                    JSONObject sceneAction = showBroadcastActions.getJSONObject(i);
                                    String serialPortType = sceneAction.getString("portType");
                                    String key = sceneAction.getString("key");
                                    int delay = sceneAction.getIntValue("delay");
                                    if ("custom".equals(key)) {
                                        sendCtrlSerialCode(serialPortType, sceneAction.getString("code"), System.currentTimeMillis() + delay);
                                    } else {
                                        if (defaultActionCodeMap.containsKey(key)) {
                                            sendCtrlSerialCode(serialPortType, defaultActionCodeMap.get(key), System.currentTimeMillis() + delay);
                                        }
                                    }
                                }

                            } else if ("6".equals(signalType) && broadSceneConfigObj.containsKey("showRecorderActions")) {
                                JSONArray showRecorderActions = broadSceneConfigObj.getJSONArray("showRecorderActions");
                                for (int i = 0; i < showRecorderActions.size(); i++) {
                                    JSONObject sceneAction = showRecorderActions.getJSONObject(i);
                                    String serialPortType = sceneAction.getString("portType");
                                    String key = sceneAction.getString("key");
                                    int delay = sceneAction.getIntValue("delay");
                                    if ("custom".equals(key)) {
                                        sendCtrlSerialCode(serialPortType, sceneAction.getString("code"), System.currentTimeMillis() + delay);
                                    } else {
                                        if (defaultActionCodeMap.containsKey(key)) {
                                            sendCtrlSerialCode(serialPortType, defaultActionCodeMap.get(key), System.currentTimeMillis() + delay);
                                        }
                                    }
                                }

                            }
                        }

                    }
                    break;
                case 14:
                    //电脑开机
                    switch (params1) {
                        case 1:
                            action = "open_comp";
                            break;
                        case 0:
                            action = "close_comp";
                            break;
                    }
                    if (params2 == 0) {
                        params2 = 1;
                    }
                    params.put("location", params2);
                    break;
                case 15:
                    //电视开关
                    portType = null;
                    switch (params2) {
                        case 0:
                            // T5 G
                            action = "tv_power";
                            break;
                        case 1:
                            // T5 G
                            action = "tv_power_1";
                            break;
                        case 2:
                            // T4 G
                            action = "tv_power_2";
                            break;
                        case 3:
                            // T3 G
                            action = "tv_power_3";
                            break;
                    }

                    break;
                //liuyong 通过新接口板232口发出
                case 128:
                    portType = null;
                    switch (params1) {
                        case 0:
                            // 开大屏
                            action = "open_screen";
                            break;
                        case 1:
                            // 关大屏
                            action = "close_screen";
                            break;
                    }

                    break;
                //liuyong 通过红外盒子控制电视开关
                case 240:
                    portType = null;
                    switch (params2) {
                        case 0:
                            // T5 G
                            action = "tv_power";
                            break;
                        case 1:
                            // T5 G
                            action = "tv_power_1_hongwaihezi";
                            break;
                        case 2:
                            // T4 G
                            action = "tv_power_2_hongwaihezi";
                            break;
                        case 3:
                            // T3 G
                            action = "tv_power_3_hongwaihezi";
                            break;
                    }

                    break;
                case 16:
                    //低压电源控制
                    portType = null;
                    switch (params2) {
                        case 1:
                            //12V
                            switch (params1) {
                                case 0:
                                    TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PH0/data");
                                    break;
                                case 1:
                                    TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PH0/data");
                                    break;
                            }
                            break;
                        case 2:
                            //5V
                            switch (params1) {
                                case 0:
                                    TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PB15/data");
                                    break;
                                case 1:
                                    TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PB15/data");
                                    break;
                            }
                            break;
                    }
                    break;
                case 17:
                    portType = null;
                    switch (params1) {
                        case 1:
                            action = "controller_on";
                            break;
                        case 0:
                            action = "controller_off";
                            break;
                    }
                    break;
                case 18:
                    //自定义情景
                    String bSceneConfigStr = sharedPreferences.getString("c_setting_sceneConfig", null);
                    if (bSceneConfigStr == null) {
                        return;
                    }
                    JSONObject bSceneConfig = JSON.parseObject(bSceneConfigStr);
                    JSONArray customScenes = bSceneConfig.getJSONArray("customScenes");
                    if (customScenes != null && customScenes.size() > 0) {
                        for (int k = 0; k < customScenes.size(); k++) {
                            JSONObject customScene = customScenes.getJSONObject(k);
                            if (("custom" + params2).equals(customScene.getString("key"))) {
                                JSONArray sActions = customScene.getJSONArray("actions");
                                for (int i = 0; i < sActions.size(); i++) {
                                    JSONObject sceneAction = sActions.getJSONObject(i);
                                    if (!sceneAction.containsKey("key")) {
                                        continue;
                                    }
                                    String key = sceneAction.getString("key");
                                    String serialPortType = null;
                                    if (sceneAction.containsKey("portType")) {
                                        serialPortType = sceneAction.getString("portType");
                                    }
                                    int delay = 0;
                                    if (sceneAction.containsKey("delay")) {
                                        delay = sceneAction.getIntValue("delay")+800;//dzk 20231205 每个情景自定义指令加800 秒 佛科需要

                                    }
                                    if ("custom".equals(key)) {
                                        sendCtrlSerialCode(serialPortType, sceneAction.getString("code"), System.currentTimeMillis() + delay);
                                    } else {
                                        if (defaultActionCodeMap.containsKey(key)) {
                                            sendCtrlSerialCode(serialPortType, defaultActionCodeMap.get(key), System.currentTimeMillis() + delay);
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                    break;
                case 21:
                    //中控2000 可直接发
                    //portType = null;
                    //中控2050 通过自定义10发送
                    portType = "other10";
                    //sendCtrlSerialCode(null, "FE 00 02 86 02 00 03 8D FF", System.currentTimeMillis() + voiceDelay);
                    //liuyong
                    //FE 00 02 42 02 00 3F 85 FF
                    //0-40
                   if(params1 == 3){
                       if(params2 > 0 && params2 <= 64){
                           //voiceDelay = 1000;
                           //FE 00 02 42 02 00 20 66 FF
                           String ctl_instruct_pre = "FE 00 02 42 02 00 ";
                           String data = Integer.toHexString(params2+35);
                           if(data.length()<2){
                               data="0"+data;
                           }
                            String Check_Code =" " + Integer.toHexString(0x02 + 0x42 + 0x02 + Integer.parseInt(data,16));
                            String ctl_instruct_suf = " FF";
                            String ctl_instruct = ctl_instruct_pre + data + Check_Code + ctl_instruct_suf;
                           sendCtrlSerialCode(portType
                                   , ctl_instruct, System.currentTimeMillis() + 1000);
                       }else if(params2 == 0){
                           String ctl_instruct = "FE 00 02 42 02 00 00 46 FF";
                           sendCtrlSerialCode(portType, ctl_instruct, System.currentTimeMillis() + 1000);
                       }
                   }
                    /*
                    switch (params3) {
                        case 1:
                            //设备音量
                            switch (params1) {
                                case 0:
                                    action = "voice_down";
                                    break;
                                case 1:
                                    action = "voice_up";
                                    break;
                                case 2:
                                    action = "voice_no";
                                    break;
                            }
                            break;
                        case 2:
                            //话筒音量
                            switch (params1) {
                                case 0:
                                    action = "speaker_voice_down";
                                    break;
                                case 1:
                                    action = "speaker_voice_up";
                                    break;
                            }
                            break;
                        case 3:
                            switch (params1) {
                                case 0:
                                    action = "inner_mute";
                                    break;
                                case 1:

                                    break;
                            }
                            break;
                    }
                    break;*/

                case 22:
                    switch (params1) {
                        case 0:
                            action = "platform_screen_off";
                            break;
                        case 1:
                            action = "platform_screen_on";
                            break;
                    }
                    break;
                case 23:
                    switch (params1) {
                        case 0:
                            action = "loud_speaker_off";
                            break;
                        case 1:
                            action = "loud_speaker_on";
                            break;
                    }
                    break;
                case 24:
                    //风扇控制
                    portType = "ZIGBEE";
                    JSONArray fanArray = new JSONArray();
                    switch (params1) {
                        case 0:
                            action = "close_fan";
                            if (params2 == 255) {
                                for (int i = 1; i <= 12; i++) {
                                    fanArray.add(i);
                                }
                            } else {
                                fanArray.add(params2);
                            }

                            break;
                        case 1:
                            action = "open_fan";
                            if (params2 == 255) {
                                for (int i = 1; i <= 12; i++) {
                                    fanArray.add(i);
                                }
                            } else {
                                fanArray.add(params2);
                            }
                            break;
                    }
                    params.put("location", fanArray);
                    break;
                case 25:
                    //liuyong
                    //电源开关
                    portType = null;
                    switch (params1) {
                        case 0:
                            //关闭单路电源
                            if(params2 == 1) {
                                //关闭第1路电源
                                action = "power1_off";
                                break;
                            }else if(params2 == 2){
                                //关闭第2路电源
                                action = "power2_off";
                                break;
                            }else if(params2 == 3){
                                //关闭第3路电源
                                action = "power3_off";
                                break;
                            }else if(params2 == 4){
                                //关闭第4路电源
                                action = "power4_off";
                                break;
                            }else if(params2 == 5){
                                //关闭第5路电源
                                action = "power5_off";
                                break;
                            }else if(params2 == 6){
                                //关闭第6路电源
                                action = "power6_off";
                                break;
                            }else if(params2 == 7){
                                //关闭第7路电源
                                action = "power7_off";
                                break;
                            }else if(params2 == 8){
                                //关闭第8路电源
                                action = "power8_off";
                                break;
                            }
                            break;
                        case 1:
                            //打开单路电源
                            if(params2 == 1) {
                                //关闭第1路电源
                                action = "power1_on";
                                break;
                            }else if(params2 == 2){
                                //关闭第2路电源
                                action = "power2_on";
                                break;
                            }else if(params2 == 3){
                                //关闭第3路电源
                                action = "power3_on";
                                break;
                            }else if(params2 == 4){
                                //关闭第4路电源
                                action = "power4_on";
                                break;
                            }else if(params2 == 5){
                                //关闭第5路电源
                                action = "power5_on";
                                break;
                            }else if(params2 == 6){
                                //关闭第6路电源
                                action = "power6_on";
                                break;
                            }else if(params2 == 7){
                                //关闭第7路电源
                                action = "power7_on";
                                break;
                            }else if(params2 == 8){
                                //关闭第8路电源
                                action = "power8_on";
                                break;
                            }
                            break;
                        case 225:
                            //打开全部电源
                            action = "power_all_on";
                            break;
                        case 224:
                            //关闭全部电源
                            action = "power_all_off";
                            break;
                    }
                    break;
            }
            // Log.e("serial",action+","+JSON.toJSONString(action)+","+portType);
            if (action != null) {
                Bus.getInstance().emit("exec_action", action, params, portType, 5);
            }

        }


    }


    private void respBroadCode(String code, boolean resend) {
        USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", code);
        if (resend) {
            USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", code, System.currentTimeMillis() + 800);
        }
    }

    public void sendLogMessage(SerialMessage serialMessage) {
        if (BuildConfig.DEBUG) {
            Log.e("SERIAL", serialMessage.getDirection() + "," + serialMessage.getPort() + "," + serialMessage.getMessage());
            Message message = new Message();
            message.what = 3;
            message.obj = serialMessage;
            handler.sendMessage(message);
        }
        if (debugEnable) {
            JSONObject serialCodeObj = new JSONObject();
            serialCodeObj.put("action", "serial_code");
            serialCodeObj.put("type", serialMessage.getDirection().toLowerCase());
            serialCodeObj.put("port", serialMessage.getPort());
            serialCodeObj.put("code", serialMessage.getMessage());
            Bus.getInstance().emit("publish_feedback_msg", serialCodeObj);
        }
    }

    public void dettachContext(Context context) {
        try{
            if (usbReceiver != null) {
                context.unregisterReceiver(usbReceiver);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private int controlTransfer(UsbDeviceConnection usbDeviceConnection, int request,
                                int value, int index) {
        if (usbDeviceConnection == null) {
            return -1;
        }
        return usbDeviceConnection.controlTransfer(64, request, value, index, (byte[]) null, 0, 500);
    }


    private int controlTransfer(UsbDeviceConnection usbDeviceConnection, int request,
                                int value, int index, byte[] buffer, int length) {
        if (usbDeviceConnection == null) {
            return -1;
        }
        return usbDeviceConnection.controlTransfer(192, request, value, 0, buffer, length, 500);
    }

    public USBMap uartInit(UsbDevice usbDevice) {
        String baudRate = "9600";
        SerialportInfo serialportInfo = serialportConfigs.get(getPortByPath(usbDevice.getDeviceName()));
        if (serialportInfo != null) {
            String br = serialportInfo.getBaudRate();
            if (br != null && br.length() > 0) {
                baudRate = br;
            }
        }

        UsbDeviceConnection usbDeviceConnection = um.openDevice(usbDevice);
        byte[] var2 = new byte[8];
        controlTransfer(usbDeviceConnection, 161, 0, 0);
        if (controlTransfer(usbDeviceConnection, 95, 0, 0, var2, 2) < 0) {
            return null;
        } else {
            controlTransfer(usbDeviceConnection, 154, 4882, 55682);
            controlTransfer(usbDeviceConnection, 154, 3884, 4);
            if (controlTransfer(usbDeviceConnection, 149, 9496, 0, var2, 2) < 0) {
                return null;
            } else {
                controlTransfer(usbDeviceConnection, 154, 10023, 0);
                controlTransfer(usbDeviceConnection, 164, 255, 0);
                int interfaceCount = usbDevice.getInterfaceCount();
                UsbEndpoint mUsbSendEndpoint = null;
                UsbEndpoint mUsbRevEndpoint = null;
                for (int i = 0; i < interfaceCount; i++) {
                    UsbInterface usbInterface = usbDevice.getInterface(i);
                    if (usbInterface.getInterfaceClass() == 255 && usbInterface.getInterfaceSubclass() == 1 && usbInterface.getInterfaceProtocol() == 2) {
                        usbDeviceConnection.claimInterface(usbInterface, true);
                        for (int j = 0; j < usbInterface.getEndpointCount(); ++j) {
                            UsbEndpoint usbEndpoint = usbInterface.getEndpoint(j);
                            if (usbEndpoint.getType() == 2 && usbEndpoint.getMaxPacketSize() == 32) {
                                if (usbEndpoint.getDirection() == 128) {
                                    mUsbRevEndpoint = usbEndpoint;
                                } else {
                                    mUsbSendEndpoint = usbEndpoint;
                                }
                            }

                        }

                        break;
                    }
                }
                if (mUsbRevEndpoint == null || mUsbSendEndpoint == null) {
                    return null;
                }
                SetConfig(usbDeviceConnection, parseInt(baudRate), dataBit, stopBit, parity, flowControl);
                return new USBMap(usbDevice.getDeviceName(), usbDeviceConnection, mUsbSendEndpoint, mUsbRevEndpoint);
            }
        }

    }

    public String getPortName(String port) {
        if (port == null) {
            return "未知设备";
        }
        String name = nameRef.get(port);
        if (name == null) {
            name = port;
        }
        return name;
    }

    public String getPortByPath(String path) {
        if (path == null) {
            return null;
        }
        for (String key : portRef.keySet()) {
            String pathRule = portRef.get(key);
            if (pathRule.endsWith("*")) {
                if (path.startsWith(pathRule.replace("*", ""))) {
                    dymicPortRef.put(key, path);
                    return key;
                }
            } else {
                if (path.equals(pathRule)) {
                    return key;
                }
            }
        }
        return null;
    }

    public void clearCtrlSerialCode(String portType) {
//        if (portType == null) {
//            codeQueueMap.put(MAIN_TTL_PORT,new HexCodeQueue());
//        }
    }

    public void sendCtrlSerialCode(String message) {
        sendCtrlSerialCode(null, message, System.currentTimeMillis());
    }

    public void sendStatusSerialCode(String message) {
        sendStatusSerialCode(null, message, System.currentTimeMillis());
    }

    public void sendCtrlSerialCode(String portType, String message) {
        sendCtrlSerialCode(portType, message, System.currentTimeMillis());
    }

    public void sendStatusSerialCode(String portType, String message) {
        sendStatusSerialCode(portType, message, System.currentTimeMillis());
    }

    public void sendCtrlSerialCode(String portType, String message, long time) {
        //控制指令
        if (portType == null || "ttl".equalsIgnoreCase(portType)) {
            HexCodeQueue hexCodeQueue = codeQueueMap.get(MAIN_TTL_PORT);
            if (hexCodeQueue == null) {
                hexCodeQueue = new HexCodeQueue();
                codeQueueMap.put(MAIN_TTL_PORT, hexCodeQueue);
            }
            hexCodeQueue.addCtrlSerialCode(new SerialHexCode(message, time));
        } else if (controllerVersion.equals(ControllerVersion.OLD) && portType.equals(HDMIMATRIX)) {
            HexCodeQueue hexCodeQueue = codeQueueMap.get(HDMI_TTL_PORT);
            if (hexCodeQueue == null) {
                hexCodeQueue = new HexCodeQueue();
                codeQueueMap.put(HDMI_TTL_PORT, hexCodeQueue);
            }
            hexCodeQueue.addCtrlSerialCode(new SerialHexCode(message, time));
        } else {
            for (Map.Entry<String, SerialportInfo> entry : serialportConfigs.entrySet()) {
                if (portType.equals(entry.getValue().getPortName())) {
                    HexCodeQueue hexCodeQueue = codeQueueMap.get(entry.getKey());
                    if (hexCodeQueue == null) {
                        hexCodeQueue = new HexCodeQueue();
                        codeQueueMap.put(entry.getKey(), hexCodeQueue);
                    }
                    hexCodeQueue.addCtrlSerialCode(new SerialHexCode(message, time));
                }
            }

        }
        if (CONTROLPANEL.equals(portType)) {
            HexCodeQueue hexCodeQueue = codeQueueMap.get("TCP");
            if (hexCodeQueue == null) {
                hexCodeQueue = new HexCodeQueue();
                codeQueueMap.put("TCP", hexCodeQueue);
            }
            hexCodeQueue.addCtrlSerialCode(new SerialHexCode(message, time));
        }

    }


    public void sendStatusSerialCode(String portType, String message, long time) {

        Log.d("dzk", "sendStatusSerialCode: "+portType+"------->"+message);
        //状态指令
        if (portType == null) {
            HexCodeQueue hexCodeQueue = codeQueueMap.get(MAIN_TTL_PORT);
            if (hexCodeQueue == null) {
                hexCodeQueue = new HexCodeQueue();
                codeQueueMap.put(MAIN_TTL_PORT, hexCodeQueue);
            }
            hexCodeQueue.addStatusSerialCode(new SerialHexCode(message, time));
        } else {
            for (Map.Entry<String, SerialportInfo> entry : serialportConfigs.entrySet()) {
                if (portType.equals(entry.getValue().getPortName())) {
                    HexCodeQueue hexCodeQueue = codeQueueMap.get(entry.getKey());
                  //  if (hexCodeQueue == null) {
                        hexCodeQueue = new HexCodeQueue();
                        codeQueueMap.put(entry.getKey(), hexCodeQueue);
                 //   }
                    hexCodeQueue.addStatusSerialCode(new SerialHexCode(message, time));
                }
            }

        }

    }


    public void sendStatusSerialCode(String portType, String message, long time, String key) {
        //状态指令
        if (portType == null) {
            HexCodeQueue hexCodeQueue = codeQueueMap.get(MAIN_TTL_PORT);
            if (hexCodeQueue == null) {
                hexCodeQueue = new HexCodeQueue();
                codeQueueMap.put(MAIN_TTL_PORT, hexCodeQueue);
            }
            hexCodeQueue.addStatusSerialCode(new SerialHexCode(message, time, key));
        } else {
            for (Map.Entry<String, SerialportInfo> entry : serialportConfigs.entrySet()) {
                if (portType.equals(entry.getValue().getPortName())) {
                    HexCodeQueue hexCodeQueue = codeQueueMap.get(entry.getKey());
                    if (hexCodeQueue == null) {
                        hexCodeQueue = new HexCodeQueue();
                        codeQueueMap.put(entry.getKey(), hexCodeQueue);
                    }
                    hexCodeQueue.addStatusSerialCode(new SerialHexCode(message, time, key));
                }
            }
        }
    }


    public void sendSerialMessageFromPort(String port, boolean isUSB, @NonNull String message) {
        String mMsg = message.replaceAll(" ", "").toLowerCase();
        long now = System.currentTimeMillis();
        if ("fe000282010085ff".equals(mMsg) || "ceee039900eeec".equals(mMsg)) {
            inClass = false;
            sendCtrlSerialCode("controlpanel", "CEEE040100EEEC", now + 1500);
            // sendCtrlSerialCode("controlpanel", "CEEE040100EEEC", now + 1000);
            String broadConfigStr = sharedPreferences.getString("broadConfig", null);
            if (broadConfigStr == null || broadConfigStr.length() == 0) {
                sendCtrlSerialCode("controlpanel", "CEEE030000EEEC", now + 30000);
                //sendCtrlSerialCode("controlpanel", "CEEE030000EEEC", now + 2000);
            } else {
                JSONObject broadConfig = JSON.parseObject(broadConfigStr);
//                if (broadConfig.getBooleanValue("lock")) {
//                    String openType = broadConfig.getString("openType");
//                    if ("1".equals(openType)) {
//                        sendCtrlSerialCode("controlpanel", "ceee030100eeec", now + 30000);
//                        //    sendCtrlSerialCode("controlpanel", "ceee030100eeec", now + 2000);
//                    } else if ("2".equals(openType)) {
//                       // sendCtrlSerialCode("controlpanel", "ceee030200eeec", now + 30000); //dzk 20240117 测试理工下课没到时间就跳转
//                        //sendCtrlSerialCode("controlpanel", "ceee030200eeec", now + 2000);
//                    }
//                } else {
//                    sendCtrlSerialCode("controlpanel", "ceee030000eeec", now + 30000);
//                    // sendCtrlSerialCode("controlpanel", "ceee030000eeec", now + 2000);
//                }
            }

        } else if ("fe000282010186ff".equals(mMsg)) {
            Bus.getInstance().emit("scene_event", "on_class");
            inClass = true;
            //dzk 20231204 为了佛科注释
           sendCtrlSerialCode("controlpanel", "CEEE040101EEEC", now + 500);
        } else if ("cffc0f08fe00020901010dfffccf".equals(mMsg)) {
            //12V通电
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PH0/data");
            return;
        } else if ("cffc0f08fe00020901000cfffccf".equals(mMsg)) {
            //12V断电
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PH0/data");
            return;
        } else if ("cffc0f08fe00020902010efffccf".equals(mMsg)) {
            //5V通电
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PB15/data");
            return;
        } else if ("cffc0f08fe00020902000dfffccf".equals(mMsg)) {
            //5V断电
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PB15/data");
            return;
        } else if ("cffc0f08fe00020903010ffffccf".equals(mMsg)) {
            //备用1高电平
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PB16/data");
            return;
        } else if ("cffc0f08fe00020903000efffccf".equals(mMsg)) {
            //备用1低电平
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PB16/data");
        } else if ("cffc0f08fe000209040110fffccf".equals(mMsg)) {
            //备用2高电平
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 0 > sys/class/gpio_sw/PB17/data");
            return;
        } else if ("cffc0f08fe00020904000ffffccf".equals(mMsg)) {
            //备用2低电平
            TCWManager.getInstance(MyApplication.myApplication).execSuCmd("echo 1 > sys/class/gpio_sw/PB17/data");
            return;
        } else if (mMsg.startsWith("ceecff")) {
            doCustomAction(mMsg.substring(6).toLowerCase(), null, "controlpanel");
            return;
        } else if (mMsg.startsWith("fd") && mMsg.length() == 24 && ("0034".equals(mMsg.substring(6, 10)) || "003f".equals(mMsg.substring(6, 10)))) {
            if (!airctrlStatusEnable) {
                return;
            }
        }
        String realPortPath = null;
        if (port == null) {
            port = MAIN_TTL_PORT;
        }
        if (port.startsWith("ttyS")) {
            realPortPath = "/dev/" + port;
        } else {
            if (!portRef.containsKey(port)) {
                return;
            }
            if (dymicPortRef.containsKey(port)) {
                realPortPath = dymicPortRef.get(port);
            } else {
                realPortPath = portRef.get(port);
            }
        }
        sendSerialMessageFromPath(realPortPath, message);
    }

    public void sendSerialMessageFromPath(String path, String message) {

        if (path == null) {
            return;
        }
        if (path.contains("usb")) {
            if (!usbHashMap.containsKey(path)) {
                return;
            }
            USBMap usbMap = usbHashMap.get(path);
            byte[] to_send = hexStringToByte(message);
            if (to_send != null) {
                sendLogMessage(new SerialMessage(getPortName(getPortByPath(usbMap.getUsbPath())), message.toUpperCase(), "TX"));
                WriteData(usbMap.getUsbDeviceConnection(), usbMap.getUsbSendEndpoint(), to_send, to_send.length);
            }

        } else {
            if (!ttyRef.containsKey(path)) {
                return;
            }
            SerialPortHelper serialPortHelper = ttyRef.get(path);
            serialPortHelper.sendHex(message.replaceAll(" ", ""));
            sendLogMessage(new SerialMessage(path.substring(path.lastIndexOf("/") + 1), message.toUpperCase(), "TX"));
        }

    }

    private String byte2HexString(byte[] arg, int length) {
        String result = new String();
        if (arg != null) {
            for (int i = 0; i < length; i++) {
                result = result
                        + (Integer.toHexString(
                        arg[i] < 0 ? arg[i] + 256 : arg[i]).length() == 1 ? "0"
                        + Integer.toHexString(arg[i] < 0 ? arg[i] + 256
                        : arg[i])
                        : Integer.toHexString(arg[i] < 0 ? arg[i] + 256
                        : arg[i])) + " ";
            }
            return result;
        }
        return "";
    }


    private byte[] hexStringToByte(String hex) {
        if (com.leectrl.utils.HexUtil.isHexStr(hex)) {
            hex = hex.replaceAll(" ", "");
            int len = (hex.length() / 2);
            byte[] result = new byte[len];
            for (int i = 0; i < len; i++) {
                result[i] = (byte) (parseInt(hex.substring(i * 2, (i + 1) * 2), 16) & 0xff);
            }
            return result;
        }
        return null;
    }


    public boolean SetConfig(UsbDeviceConnection usbDeviceConnection, int var1, byte var2,
                             byte var3, byte var4, byte var5) {
        char var10;
        switch (var4) {
            case 0:
                var10 = 0;
                break;
            case 1:
                var10 = '\b';
                break;
            case 2:
                var10 = 24;
                break;
            case 3:
                var10 = '(';
                break;
            case 4:
                var10 = '8';
                break;
            default:
                var10 = 0;
        }

        if (var3 == 2) {
            var10 = (char) (var10 | 4);
        }

        switch (var2) {
            case 5:
                var10 = (char) var10;
                break;
            case 6:
                var10 = (char) (var10 | 1);
                break;
            case 7:
                var10 = (char) (var10 | 2);
                break;
            case 8:
                var10 = (char) (var10 | 3);
                break;
            default:
                var10 = (char) (var10 | 3);
        }

        var10 = (char) (var10 | 192);
        int var7 = 156 | var10 << 8;
        byte var6;
        short var9;
        switch (var1) {
            case 50:
                var6 = 0;
                var9 = 22;
                break;
            case 75:
                var6 = 0;
                var9 = 100;
                break;
            case 110:
                var6 = 0;
                var9 = 150;
                break;
            case 135:
                var6 = 0;
                var9 = 169;
                break;
            case 150:
                var6 = 0;
                var9 = 178;
                break;
            case 300:
                var6 = 0;
                var9 = 217;
                break;
            case 600:
                var6 = 1;
                var9 = 100;
                break;
            case 1200:
                var6 = 1;
                var9 = 178;
                break;
            case 1800:
                var6 = 1;
                var9 = 204;
                break;
            case 2400:
                var6 = 1;
                var9 = 217;
                break;
            case 4800:
                var6 = 2;
                var9 = 100;
                break;
            case 9600:
                var6 = 2;
                var9 = 178;
                break;
            case 19200:
                var6 = 2;
                var9 = 217;
                break;
            case 38400:
                var6 = 3;
                var9 = 100;
                break;
            case 57600:
                var6 = 3;
                var9 = 152;
                break;
            case 115200:
                var6 = 3;
                var9 = 204;
                break;
            case 230400:
                var6 = 3;
                var9 = 230;
                break;
            case 460800:
                var6 = 3;
                var9 = 243;
                break;
            case 500000:
                var6 = 3;
                var9 = 244;
                break;
            case 921600:
                var6 = 7;
                var9 = 243;
                break;
            case 1000000:
                var6 = 3;
                var9 = 250;
                break;
            case 2000000:
                var6 = 3;
                var9 = 253;
                break;
            case 3000000:
                var6 = 3;
                var9 = 254;
                break;
            default:
                var6 = 2;
                var9 = 178;
        }

        var1 = (var1 = 0 | 136 | var6) | var9 << 8;
        var1 = this.controlTransfer(usbDeviceConnection, 161, var7, var1);
        if (var5 == 1) {
            boolean var8 = false;
            var8 = true;
            byte var11 = 96;
            this.controlTransfer(usbDeviceConnection, 164, ~var11, 0);
        }

        return var1 >= 0;
    }

    private int ReadData(String usbPath, byte[] mBytes, int timeout) {
        if (usbHashMap.containsKey(usbPath)) {
            USBMap usbMap = usbHashMap.get(usbPath);
            if (usbMap == null) {
                return 0;
            }
            int length = usbMap.getUsbDeviceConnection().bulkTransfer(usbMap.getUsbRevEndpoint(), mBytes, mBytes.length, timeout);

            return length;
        } else {
            return 0;
        }
    }

    public int WriteData(UsbDeviceConnection usbDeviceConnection, UsbEndpoint ue,
                         byte[] var1, int var2) {
        return this.WriteData(usbDeviceConnection, ue, var1, var2, this.w);
    }

    public int WriteData(UsbDeviceConnection usbDeviceConnection, UsbEndpoint ue,
                         byte[] var1, int var2, int var3) {
        synchronized (this.j) {
        }
        int var5 = 0;
        int var7;
        var7 = var2;

        while (var5 < var2) {
            int var15 = 0;
            try {
                byte[] var8 = new byte[var15 = Math.min(var7, ue.getMaxPacketSize())];
                if (var5 == 0) {
                    System.arraycopy(var1, 0, var8, 0, var15);
                } else {
                    System.arraycopy(var1, var5, var8, 0, var15);
                }

                if ((var15 = usbDeviceConnection.bulkTransfer(ue, var8, var15, var3)) < 0) {
                    return -2;
                }
            } catch (Throwable var13) {
                throw var13;
            }

            var5 += var15;
            var7 -= var15;
        }

        return var5;
    }


    public boolean attachUSB(UsbDevice device) {
        registedDevices.add(device.getDeviceName());
        USBMap usbMap = uartInit(device);
        if (usbMap == null) {
            return false;
        }
        usbHashMap.put(device.getDeviceName(), usbMap);
        SerialDataReadThread serialDataReadThread = new SerialDataReadThread();
        serialDataReadThread.setUSBMap(usbMap);
        serialDataReadThread.start();
        return true;
    }


    public void dettachUSB(UsbDevice device) {
        usbHashMap.remove(device.getDeviceName());
    }


    class SerialDataReadThread extends Thread {
        private USBMap mUsbMap = null;
        private TemporarySerialHexMessage temporarySerialHexMessage;
        private long mSerialCodeInterval = serialCodeInterval;

        public void setUSBMap(USBMap usbMap) {
            mUsbMap = usbMap;
            String port = getPortByPath(usbMap.getUsbPath());
            SerialportInfo serialportInfo = serialportConfigs.get(port);
            if (serialportInfo != null) {
                if ("cardreader".equals(serialportInfo.getPortName())) {
                    mSerialCodeInterval = 60;
                } else if (CONTROLPANEL.equals(serialportInfo.getPortName())) {
                    mSerialCodeInterval = 120;
                }

            }
        }

        @Override
        public void run() {
            super.run();

            while (!isInterrupted()) {
                if (mUsbMap != null) {
                    synchronized (mUsbMap) {
                        byte[] buffer = new byte[4096];
                        int length = ReadData(mUsbMap.getUsbPath(), buffer, 1000);
                        String hexString = "";
                        if (length > 0) {
                            hexString = byte2HexString(buffer, length);
                        }
                        if (temporarySerialHexMessage == null) {
                            temporarySerialHexMessage = new TemporarySerialHexMessage();
                            temporarySerialHexMessage.setCode(hexString);
                            temporarySerialHexMessage.setLastTime(System.currentTimeMillis());
                        } else {
                            long dur = System.currentTimeMillis() - temporarySerialHexMessage.getLastTime();
                            if (hexString.length() > 0) {
                                if (dur <= mSerialCodeInterval) {
                                    //小于接收间隔，拼接码
                                    String receiveCode = temporarySerialHexMessage.getCode() + hexString;
                                    temporarySerialHexMessage = new TemporarySerialHexMessage();
                                    temporarySerialHexMessage.setCode(receiveCode);
                                    temporarySerialHexMessage.setLastTime(System.currentTimeMillis());
                                } else {
                                    //大于接收间隔，将上一次接收的数据回调
                                    String receiveCode = temporarySerialHexMessage.getCode();
                                    if (receiveCode.length() > 0) {
                                        String usbPath = getPortByPath(mUsbMap.getUsbPath());
                                        sendLogMessage(new SerialMessage(getPortName(usbPath), receiveCode.toUpperCase(), "RX"));
                                        onReceiveSerialCode(usbPath, receiveCode.toUpperCase());
                                    }
                                    temporarySerialHexMessage = new TemporarySerialHexMessage();
                                    temporarySerialHexMessage.setCode(hexString);
                                    temporarySerialHexMessage.setLastTime(System.currentTimeMillis());
                                }
                            } else {
                                if (dur >= mSerialCodeInterval) {
                                    String receiveCode = temporarySerialHexMessage.getCode();
                                    if (receiveCode.length() > 0) {
                                        String usbPath = getPortByPath(mUsbMap.getUsbPath());
                                        sendLogMessage(new SerialMessage(getPortName(usbPath), receiveCode.toUpperCase(), "RX"));
                                        onReceiveSerialCode(usbPath, receiveCode.toUpperCase());
                                    }
                                    temporarySerialHexMessage = new TemporarySerialHexMessage();
                                    temporarySerialHexMessage.setCode("");
                                    temporarySerialHexMessage.setLastTime(System.currentTimeMillis());
                                }
                            }
                        }
                    }

                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }


        }
    }


    class USBReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                // 获取权限结果的广播
                synchronized (this) {
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device != null) {

                        //call method to set up device communication
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            Log.e("aaa", device.getDeviceName() + "请求权限");
                            boolean initRes = attachUSB(device);
                            sendLogMessage(new SerialMessage(getPortName(getPortByPath(device.getDeviceName())), initRes ? "初始化成功" : "初始化失败", "SYS"));
                        }
                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                // 有新的设备插入了，在这里一般会判断这个设备是不是我们想要的，是的话就去请求权限
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                if (registedDevices.contains(device.getDeviceName())) {
                    synchronized (this) {
                        if (device != null) {
                            sendLogMessage(new SerialMessage(getPortName(getPortByPath(device.getDeviceName())), "设备插入", "SYS"));
                            if (um.hasPermission(device)) {
                                boolean initRes = attachUSB(device);
                                // Log.e("aaa", device.getDeviceName() + "=>" + initRes);
                                String port = getPortByPath(device.getDeviceName());
                                sendLogMessage(new SerialMessage(getPortName(port), initRes ? "初始化成功" : "初始化失败", "SYS"));
                                if (initRes) {
//                                    Timer timer = new Timer();
//                                    timer.scheduleAtFixedRate(new TimerTask() {
//                                        @Override
//                                        public void run() {
//                                            HexCodeQueue hexCodeQueue = codeQueueMap.get(port);
//                                            if (hexCodeQueue == null) {
//                                                return;
//                                            }
//                                            SerialHexCode serialHexCode = hexCodeQueue.getFirstOveredCode();
//                                            if (serialHexCode != null) {
//                                                String serialKey = serialHexCode.getKey();
//                                                if (serialKey != null) {
//                                                    setSerialKey(port, serialKey);
//                                                }
//                                                sendSerialMessageFromPort(port, true, serialHexCode.getCode().replaceAll(" ", ""));
//                                            }
//                                        }
//                                    }, 0, 300);

                                }
                                SerialportInfo serialportInfo = serialportConfigs.get(port);
                                if (serialportInfo != null) {
                                    serialQueueMap.put(port, serialportInfo);
                                    if ("cardreader".equals(serialportInfo.getPortName())) {
                                        sendSerialMessageFromPort(port, true, "FE010300ED0594D7FFFF");
                                    }
                                }
                            } else {
                                permissionReqArr.add(device);
                                handler.sendEmptyMessageDelayed(1, 1000);
                            }
                        }
                    }
                } else {
                    if (String.format("%04x:%04x", device.getVendorId(), device.getProductId()).equals("1a86:7523")) {
                        //  TCWManager.getInstance(mContext).reboot();
                    }
                }

            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                // 有设备拔出了
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device != null) {
                    sendLogMessage(new SerialMessage(getPortName(getPortByPath(device.getDeviceName())), "设备拔出", "SYS"));
                    dettachUSB(device);
                }
            }
        }
    }

}
